且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在实体框架中使用存储过程,如何使实体具有其导航属性的填充?

更新时间:2023-12-05 12:16:16

好的存储过程不可组合。所以没有办法调用您的SPROC,并且使用Include()或其他东西在EF中自动填充相同的查询关系。



所以说你有产品和类别



您有一个sproc可以获得产品:



ie

  var products = context.GetProducts(someproductfilter); 

所生成的产品不会加载其类别。



但是,如果您有第二个存储过程获取所述产品的类别:



ie

  var categories = context.GetCategoriesForProducts(someproductfilter); 

EF中的一个功能称为关系修复,一旦第二个实体进入上下文,它将链接相关实体,将确保在两个电话完成后,产品中的每个产品都将具有非空类别。



这不是理想的,因为您正在执行多个查询,但是它将工作。



另一种方法是使用 EFExtensions 。写的这个人创造了一个写入sprocs的能力,一次加载更多的数据。



希望这有助于



Cheers
Alex


Entity framework is cripplingly slow so I tried using a stored procedure but I ran into this problem.

Entity Framework allows you to define a stored procedure that produces an entity. However my entity has 'navigation properties' which are not being populated when using this method.

Is there a work around?

Well stored procedures are not composable. So there is no way to call your SPROC and have the EF automatically populate relationships in the same query, using Include() or something.

So say you have products and categories

and you have a sproc to get Products:

i.e.

var products = context.GetProducts(someproductfilter);

the resulting products won't have their categories loaded.

However if you have a second stored procedure that gets the Categories for said products:

i.e.

var categories = context.GetCategoriesForProducts(someproductfilter);

a feature in EF called relationship fixup, which links related entities once the second entity enters the context, will insure that after both calls are made, each product in products will have a non-null Category.

This is not ideal, because you are doing more than one query, but it will work.

An alternative is to use EFExtensions. The guy who wrote that created the ability to write sprocs that load more data in one go.

Hope this helps

Cheers Alex