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

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

问题描述

我想获得一个导航属性​​的外键的值,而不必定义外键属性(导航属性加载之前)。

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).

为什么?

我们缓存(举例)所有身份-objects应用广泛(是的,我们不能用枚举此)。当我们有一个导航属性​​这个状态类加载的对象存储库的属性设置为缓存项。

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.

我可以用一个外键物业走了,但由于EF知道的关键,我想获得它的EF(也许通过RelationshipManager或DBEntityReference的导航属性),但我似乎无法找到它。

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.

注意的:我使用的EF5,code首先在.net 4.5

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

推荐答案

我找到了答案(上计算器)从<一个href="http://stackoverflow.com/questions/12334534/how-to-get-foreign-key-value-for-independent-association-without-hitting-databas?rq=1">Slauma (不知道我是否应该纪念这个作为重复的?)。我不得不改变codeA痘痘处理多个关系的实体。很多东西还是丑陋的,但它的工作原理:)

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;

唯一的缺点是,(据我可以告诉。希望有人找到一个更好的办法?)这些​​信息,只要你脱离实体或当你AsNoTracking()。

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天全站免登陆