ThenInclude not working for an Entity Framework LINQ query [duplicate]

≡放荡痞女 提交于 2021-01-26 09:16:51

问题


I have a database model like this:

public class Customer
{
    public int CustomerId{ get; set; }

    public int OrderId { get; set; }
    public ICollection<Order> Orders { get; set; }
}

public class Order
{
    public int OrderId { get; set; }
    public int Amount { get; set; }

    public int ProductId { get; set; }
    public Product Product { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
}

So we have a customer which can do an order. This order includes a product and this includes a name. I'm now trying to return the complete model with a linq statement like the following:

_db.Customer.Include(c => c.Orders).ThenInclude(o => o.Product).SingleOrDefaultAsync();

But ThenInclude(o => o.Product) doesn't function because Orders is an ICollection. Greetings from Germany and thanks in advance for any help.


回答1:


To load related entities in EF 6 you should use Select method as I show below:

_db.Customer.Include(c => c.Orders.Select(o=>o.Product)).SingleOrDefaultAsync();

ThenInclude method was added in EF Core, which is the last version of EF.




回答2:


May be wrong here but wouldn;t you need to change:

public class Order
{
    public int OrderId { get; set; }
    public int Amount { get; set; }

    public int ProductId { get; set; }
    public Product Product { get; set; }
}

to

public class Order
{
    [Key, ForeignKey("Product")]
    public int OrderId { get; set; }
    public int Amount { get; set; }

    public int ProductId { get; set; }
    public virtual Product Product { get; set; }
}

in order for this to behave the way you are expecting.



来源:https://stackoverflow.com/questions/42725488/theninclude-not-working-for-an-entity-framework-linq-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!