如何在实体框架中自动包含所有基础导航属性 [英] How to include all underlying navigation properties automatically with entity framework

查看:59
本文介绍了如何在实体框架中自动包含所有基础导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景:我想向数据库添加一个具有导航属性的实体,而那个实体具有导航属性..依此类推.基本上,数据库中的表是相互连接的-所有的表都如此.

Scenario: I'd like to add an entity to the database that would have navigation properties and that entity has navigation properties.. and so on. Basically the tables in the database are connected with each other - all of them.

我使用EF4.3和上下文/请求模式,所以我不想启用延迟加载;只需花费太多时间来加载我需要的实体.到目前为止,我已经了解到,除了使用如下所示的include方法外,没有其他方法可以做到:

I use EF4.3 and context/request pattern, so I don't want to enable Lazy loading; it would simply just take too much time to load the entity that I need. So far I have learned there is no other way to do it than to use the include method like this:

 context.Set<TEntity>().include("navproperty1").include("navproperty1.navproperty1.1")... and so on.

这种方式的可维护性很差,而且代码很多,但是如果我不想为每种实体类型手动编写所有包含项,还有其他方法吗?

This way the maintainability would be bad, plus it's a lot of code but is there any other way if I don't want to manually write all the includes for every entity type?

推荐答案

这里有很多问题.我会尽力解决每个问题.

There are a lot of questions here. I'll try to address each point.

首先,延迟加载并不总是更快.特别是如果您正在加载所有关系.

First, Lazy loading isn't always faster. Specially if you are loading ALL the relations.

第二,请始终避免使用魔术字符串".我不知道接收到lambda表达式(它是IQueryable扩展名)的 Include 方法是否可用于EF 4.3.如果不是,则应该自己实现如此处所示并使用:

Second, always avoid "magic strings". I don't know if the Include method which receives a lambda expression (it's an IQueryable extension) is available for EF 4.3. If it's not, you should implement it yourself like shown here and use:

context.Set<TEntity>().include(t => t.NavProp)

"A"实体与"B"实体具有1:n的关系,但"B"实体具有n:m与"C"实体的关系.如果我不愿意将"C"包括为"A",然后尝试调用context.SaveChanges(),则所有数据之间将丢失"B"和"C"

"A" entity" has 1 : n relation to "B" entity but "B" entity has n : m relation to "C" entity. And if I wouldnt inlcude "C" to "A" and then try to call context.SaveChanges() then all the data would lost between "B" and "C"

我真的不明白你的意思.但是,如果要选择一个属于列表中项目的子导航属性,则应在EF 5中使用此属性((不确定它是否在4.3中可用)

I don't really know what you meant. But, if you want to select a sub-navigation property which belongs to an item in a list you should use this in EF 5: (not sure if it works in 4.3)

context.Set<TEntity>().Include(t => t.Collection.Select(c => c.SubProp))

可以在此处

如果您对此报价进行澄清,也许我可以提供更多帮助.

If you clarify on that quote maybe I can help more.

这篇关于如何在实体框架中自动包含所有基础导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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