简体   繁体   English

使用实体框架过滤子记录

[英]Filter child records using Entity Framework

I have two classes Author & Book with a relationship:我有两个类AuthorBook有关系:

public class Author
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Book> Books { get; set; }
}

public class Book
{
    public int Id { get; set; }
    public int AuthorId { get; set; }
    public string BookName { get; set; }
}

DbContext : DbContext

public class LibraryDBContext : DbContext
{
    public DbSet<Author> Authors { get; set; }
    public DbSet<Book> Books { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Author>()
               .HasMany(obj => obj.Books)
               .WithOne()
               .HasForeignKey(obj => obj.AuthorId)
               .OnDelete(DeleteBehavior.Cascade)
               .IsRequired();
    }
}

Main method where the logic is written:编写逻辑的主要方法:

class Program
{
    static void Main(string[] args)
    {
        var book1 = new Book() { AuthorId = 1, BookName = "a" };
        var book2 = new Book() { AuthorId = 1, BookName = "b" };
        var book3 = new Book() { AuthorId = 1, BookName = "c" };

        var author = new Author() { Name ="a" };

        var mydbcontext = new LibraryDBContext();
        mydbcontext.Add(author);
        mydbcontext.Add(book1);
        mydbcontext.Add(book2);
        mydbcontext.Add(book3);
        mydbcontext.SaveChanges();

        // Here I am trying to get Author 1 with BookName b
        var result = mydbcontext.Authors
                                .Include(d => d.Books)
                                .Where(d => d.Id == 1 && 
                                            d.Books.Any(b => b.BookName.Equals("b")))
                                .AsNoTracking()
                                .ToList();

        Console.WriteLine(JsonConvert.SerializeObject(result));
    }
}

Output: I am getting all records from Book even though I filtered BookName b输出:即使我过滤了BookName b我也从Book获取所有记录

[
    {
        "Id": 1,
        "Name": "a",
        "Books": [
            {
                "Id": 1,
                "AuthorId": 1,
                "BookName": "a"
            },
            {
                "Id": 2,
                "AuthorId": 1,
                "BookName": "b"
            },
            {
                "Id": 3,
                "AuthorId": 1,
                "BookName": "c"
            }
        ]
    }
]

Why are all the books returned instead of just the one with BookName = b ?为什么所有的书都返回,而不仅仅是BookName = b

.Where(d => d.Id == 1 && d.Books.Any(b=>b.BookName.Equals("b")))

The above condition checks if the Author Id == 1 and if ANY of the books by the author is named b .上述条件检查Author Id == 1以及Author Id == 1任何书籍是否名为b It doesn't filter the books by the author, which has the required name.它不会按作者过滤书籍,作者具有所需的名称。

This is true for Author where Author ID == 1 as one of his 3 books has the required name and condition is satisfied.对于 Author Author ID == 1 Author 也是如此,因为他的 3 本书之一具有所需的名称并且条件得到满足。

What you would require would be你需要的是

mydbcontext.Books.Where(d => d.AuthorId== 1 && d.BookName.Equals("b"))

The above would filter the books which has AuthorId=1 and has BookName==b以上将过滤具有AuthorId=1BookName==b的书籍

Update based on comment根据评论更新

To include the Author details, you could modify the query as要包含作者详细信息,您可以将查询修改为

var result = mydbcontext.Authors
                        .Include(d => d.Books)
                        .Where(d => d.AuthorId== 1)
                        .Select(x=> 
                           new Author
                          { 
                              Id=x.Id,
                              Name=x.Name,
                              Books = x.Where(c=>c.BookName.Equals("b"))
                           });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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