检查实体框架中是否存在实体的通用方法? [英] Generic Way to Check If Entity Exists In Entity Framework?

查看:32
本文介绍了检查实体框架中是否存在实体的通用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类似于 检查对象是否存在的最佳方法在实体框架中?

我正在寻找一种通用方法来检查 DbSet 中的实体.像这样的东西,它不起作用:

I'm looking for a generic way to check for an entity in a DbSet. Something like this, which doesn't work:

private DbContext DbContext { get; set; }

private DbSet<T> DbSet { get; set; }

public Boolean Exists(T entity) {
    return ((from item in this.DbSet
             where item == entity
             select item).Count() > 0);
}

where item == entity 在 LINQ to SQL 中有效,但显然不适用于 LINQ to Entities.由于实体可能有不同的键,我不能让它们都从具有已知键的公共抽象继承以进行比较.

The line where item == entity works in LINQ to SQL, but apparently not with LINQ to Entities. Since the entities may have different keys I can't have them all inherit from a common abstract with a known key for comparison.

我可以这样做,但我担心捕获异常作为验证过程的性能这也不起作用,因为只要实体与 OriginalValues 无法获得属性:

I could do this, but I'm worried about the performance of catching exceptions as a verification process This doesn't work either since as long as the entity is detached the OriginalValues property can't be obtained:

public Boolean Exists(T entity) {
    try {
        var current = this.DbContext.Entry(entity).OriginalValues;
        // Won't reach this line if the entity isn't in the database yet
        return true;
    }
    catch (Exception ex) {
        return false;
    }
}

推荐答案

您想要通用方式检查实体是否通过上下文加载或通用方式查询数据库(如果实体存在)?

Do you want generic way to check if entity was loaded by context or generic way to query database if entity exists?

对于前一种情况使用:

public bool Exists<T>(T entity) where T: class
{
    return this.Set<T>().Local.Any(e => e == entity);
}

对于后一种情况使用(它也会检查加载的实体):

For the latter case use (it will check loaded entities as well):

public bool Exists<T>(params object[] keys)
{
    return this.Set<T>().Find(keys) != null;
}

EF 代码首先不应访问此类信息,但可以获取实体键的名称.我认为这样的事情应该可行:

EF code first is not supposed to access this kind of information but it is possible to get name of entity keys. I think something like that should work:

var objContext = ((IObjectContextAdapter)dbContext).ObjectContext;
var objSet = objContext.CreateObjectSet<T>();
var keyNames = objSet.EntitySet.ElementType.KeyMembers.Select(m => m.Name);

但这一切都没有意义.您想要通用方法,但您的实体没有共享必要的信息来允许通用方法.现在你说你甚至不知道关键值.使用这个通用"方法将需要反射和手动构建表达式树.

But this all doesn't make sense. You want generic approach but your entities doesn't share necessary information to allow generic approach. Now you say that you even don't know key values. Using this "generic" approach will require reflection and manual building of expression tree.

这篇关于检查实体框架中是否存在实体的通用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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