2

I'm trying get all records from a table that have a specific foreign key but I'm struggling to get linq to return anything useful.

Post Model

public class Post
{
    //... irrelevant properties
    [ForeignKey("Category")]
    public int CategoryId;
    public virtual Category Category { get; set; }
}

my dbo.Posts table

enter image description here

What I've tried

I've tried several variations of the following:

//id = 7

using (UnitOfWork uwork = new UnitOfWork())
{
    var post = uwork.PostRepository.GetAll().Where(c => c.CategoryId == id);

}

This only returns "Non-Public members", which doesn't contain anything useful.

enter image description here

Question

How could I modify my linq query to return all posts that have a specific Foreign Key id?


updates

here's my repository

1
  • What does the repository do on GetAll? Commented Jul 15, 2015 at 0:26

1 Answer 1

3

It seems that you are basically looking at DbQuery<T> object, which is an implementation of IQueryable<T>. Basically LINQ did not make a query yet, because no one asked it for data. So instead it collects all info about the query in an object, to execute it later when needed.

To force it to give you the actual data, simply do ToList, or iterate over posts, or anything:

var post = uwork.PostRepository.GetAll().Where(c => c.CategoryId == id).ToList();

Just make sure to do so before you expose the db context object.

Sign up to request clarification or add additional context in comments.

3 Comments

This threw an error: The specified type member 'CategoryId' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Well, that's now entire different story. Something is wrong with your ORM mapping. Looks like you have Category_Id in your table, and CategoryId in the object - that might be an issue. But the key thing is that linq did execute the query now
Agreed, looks like I need to update my model. thank you and I'll accept this as the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.