Filling child entity with Entity Framework SqlQuery

旧城冷巷雨未停 提交于 2019-12-20 04:19:49

问题


I have two entities in 1:n relationship: Category and Product.

public class Category 
{
   public int CategoryID { get; set; }
   public string CategoryName { get; set; }

   public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
   public int ProductID { get; set; }
   public string ProductName { get; set; }

  public virtual Product { get; set; }
}

public class context : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }
}

Its possible to load products in every category by Eager loading.

context.Categories.Include(c=>c.Products).ToList()

How can I load products in every category in below query same as Eager loading?

var q = @"
   SELECT Categories.*
   JOIN Products
   ON Category.CategoryId = Products.CategoryId";
var c = context.Categories.SqlQuery(q).ToList();

Its only a simple query. I need to use SqlQuery to execute some queries.


回答1:


According to this explanation you can't:

the query should be written to ensure that it only returns entities that are really of the requested type

(my emphasis)

So it's only by lazy loading (if enabled) that you can load the Products of the categories after the SqlQuery has run, which will cause n+1 queries.




回答2:


I don't think it is possible to materialize entities obtained from Sql query if the result contains multiple entity types.



来源:https://stackoverflow.com/questions/13031281/filling-child-entity-with-entity-framework-sqlquery

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