问题
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