EF 5 - 获取导航属性的外键值 [英] EF 5 - Get foreign key value for navigation property

查看:198
本文介绍了EF 5 - 获取导航属性的外键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取导航属性的外键值,而无需定义外键属性(在导入属性加载之前)。



为什么?



我们缓存(例如)所有状态 - 对象应用程序范围(是的,我们不能使用枚举)。当我们将具有导航属性的对象加载到此状态类时,存储库将将该属性设置为缓存项。



我可以使用外键属性,但是因为EF知道密钥,我想从EF获取它(可能通过RelationshipManager或导航属性的DBEntityReference),但我似乎找不到。



<注意:我正在使用EF5,代码首先在.Net 4.5中

解决方案

answer(on stackoverflow)from Slauma (不知道我是否应该将其标记为重复?)。我不得不改变代码来处理一个具有多重关系的实体。很多东西还是很丑,但是它的作用是:)

  RelationshipManager relMgr =((IObjectContextAdapter)context).ObjectContext.ObjectStateManager。 GetRelationshipManager(文件); 
IEnumerable< IRelatedEnd> relEnds = relMgr.GetAllRelatedEnds();
IRelatedEnd relEnd = relEnds.Where(r => r.RelationshipName.EndsWith(Document_Status))。Single();
EntityReference< Status> entityRef = relEnd作为EntityReference< Status> ;;;
var entityKey = entityRef.EntityKey;

short statusId =(short)entityKey.EntityKeyValues [0] .Value;

唯一的缺点是(据我所知,希望有人找到更好的方式)一旦您分离实体或使用AsNoTracking()加载它时,此信息就会丢失。


I want to get the foreign key value for a navigation property, without having to define the foreign key property (before the navigation property is loaded).

Why?

We cache (for instance) all "status"-objects application wide (yes we couldn't use enums for this). When we load an object with a navigation property to this status-class the repository will set the property to the cached item.

I could go with a foreign key property, but since EF knows the key, I would like to get it from EF (maybe through the RelationshipManager or the DBEntityReference for the navigation property) but I can't seem to find it.

Note: I am using EF5, code first in .Net 4.5

解决方案

I found an answer (on stackoverflow) from Slauma (not sure if I should mark this as duplicate?). I had to change the code a litle to handle an entity with multiple relations. A lot of stuff is still ugly but it works :)

RelationshipManager relMgr = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetRelationshipManager(document);
IEnumerable<IRelatedEnd> relEnds = relMgr.GetAllRelatedEnds();
IRelatedEnd relEnd = relEnds.Where(r => r.RelationshipName.EndsWith("Document_Status")).Single();
EntityReference<Status> entityRef = relEnd as EntityReference<Status>;
var entityKey = entityRef.EntityKey;

short statusId =(short)entityKey.EntityKeyValues[0].Value;

The only downside is that (As far as I can tell. Hope someone finds a better way?) this information is lost as soon as you detach the entity or when you load it with AsNoTracking().

这篇关于EF 5 - 获取导航属性的外键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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