实体框架4:访问部分实体类中的当前数据文本 [英] Entity Framework 4: Access current datacontext in partial entity class

查看:129
本文介绍了实体框架4:访问部分实体类中的当前数据文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用方法和属性在部分类中扩展一个EF实体。我经常这样做。
但现在我需要将来自该实体的数据与其他实体的数据进行组合。因此,我需要能够访问实体objectcontext(如果附加)来进行这些查询。
有没有办法从其中获取实体objectcontext?



Thanx!

解决方案

即使不推荐,我自己不使用它(如Ladislav所说:坏的设计),我偶然发现一个解决方案:



http://blogs.msdn.com/b/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity .aspx



扩展方法:

  public static ObjectContext GetContext(
this IEntityWithRelationships entity

{
if(entity == null)
throw new ArgumentNullException(entity);

var relationshipManager = entity.RelationshipManager;

var relatedEnd = relationshipManager.GetAllRelatedEnds()
.FirstOrDefault();

if(relevantEnd == null)
抛出新异常(找不到关系);

var query = relatedEnd.CreateSourceQuery()as ObjectQuery;

if(query == null)
throw new Exception(实体被分离);

return query.Context;
}

在实体中

  var myContext = this.GetContext()as MyEntities;  


I want to extend an EF entity in a partial class with methods and properties. I've done this quite often. But now I would need to combine data from this entity with data from other entities. I would therefore need to able to access the entities objectcontext (if attached) to make these queries. Is there a way to get the entities objectcontext from within it?

Thanx!

解决方案

Even though it is not recommended, and I myself don't use it (as Ladislav stated: bad design), I stumbled upon a solution:

http://blogs.msdn.com/b/alexj/archive/2009/06/08/tip-24-how-to-get-the-objectcontext-from-an-entity.aspx

Extension Method:

public static ObjectContext GetContext( 
   this IEntityWithRelationships entity 
) 
{ 
    if (entity == null)  
       throw new ArgumentNullException("entity"); 

    var relationshipManager = entity.RelationshipManager; 

    var relatedEnd = relationshipManager.GetAllRelatedEnds() 
                                        .FirstOrDefault(); 

    if (relatedEnd == null)  
       throw new Exception("No relationships found"); 

    var query = relatedEnd.CreateSourceQuery() as ObjectQuery; 

    if (query == null)  
       throw new Exception("The Entity is Detached"); 

    return query.Context; 
}

within the entity

var myContext = this.GetContext() as MyEntities;

这篇关于实体框架4:访问部分实体类中的当前数据文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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