使用实体框架SqlQuery填充子实体 [英] Filling child entity with Entity Framework SqlQuery

查看:85
本文介绍了使用实体框架SqlQuery填充子实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在1:n关系中有两个实体:类别和产品。

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();

它只是一个简单的查询。我需要使用SqlQuery执行一些查询。

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

推荐答案

我认为不可能实现从Sql查询获得的实体如果结果包含多个实体类型。

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

这篇关于使用实体框架SqlQuery填充子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆