简体   繁体   中英

Using Linq to get records that have specific foreign key

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

在此处输入图片说明

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.

在此处输入图片说明

Question

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


updates

here's my repository

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM