Generic Way to Check If Entity Exists In Entity Framework?

≯℡__Kan透↙ 提交于 2019-11-26 21:55:12
Ladislav Mrnka

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

For the former case use:

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);
}

Edit:

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.

Thanks to @Ladislav for getting me in the right direction. Here's the code for a generic Exists() method.

I'd like to note that this doesn't require reflection and seems to perform quite well. The only thing I'm not thrilled about is that TryGetObjectByKey() has the side-effect of attaching the found entity. Since I don't want Exists() to have that unintentional result I have to detach the entity if it was found.

public Boolean Exists(T entity) {
    var objContext = ((IObjectContextAdapter)this.DbContext).ObjectContext;
    var objSet = objContext.CreateObjectSet<T>();
    var entityKey = objContext.CreateEntityKey(objSet.EntitySet.Name, entity);

    Object foundEntity;
    var exists = objContext.TryGetObjectByKey(entityKey, out foundEntity);
    // TryGetObjectByKey attaches a found entity
    // Detach it here to prevent side-effects
    if (exists) {
        objContext.Detach(foundEntity);
    }

    return (exists);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!