How to check whether DbContext.Set<T> exists in model?

穿精又带淫゛_ 提交于 2019-12-04 07:43:39

The exception should be thrown immediately when you call Set<NotMappedEntityType> so the simplest way is to catch the exception and handle it as you need.

The complex solution requires you to browse mapping metadata and search for your mapped entity type which must have the same name as your CLR type. You can add this method in your derived context class to check existence of the entity type:

public bool Exists<TEntity>() where TEntity : class
{
    string entityName = typeof(TEntity).Name;
    ObjectContext objContext = ((IObjectContextAdapter)this).ObjectContext;
    MetadataWorkspace workspace = objContext.MetadataWorkspace;
    return workspace.GetItems<EntityType>(DataSpace.CSpace).Any(e => e.Name == entityName);
}

This is my simplified answer:

public partial class MyDbContext : DbContext
{
   public bool Exists<Tx>() where Tx : class
   {
       var attachedEntity = this.ChangeTracker.Entries<Tx>().FirstOrDefault();
       return (attachedEntity != null);
   }
}

EF Core 2.x Updated extension method: It will return NotFound if doesn't exist and DbSetType or ViewType if the entity TEntity is defined on the model.

    public enum QueryType
    {
        DbsetType,
        ViewType,
        NotFound
    }

    public static class DbContextExtensions
    {
        public static QueryType GetQueryType<TEntity>(this DbContext context) where TEntity : class
        {
            var metaData = context.Model.FindEntityType(typeof(TEntity));

            if (metaData == null)
                return QueryType.NotFound;

            return metaData.IsQueryType ? QueryType.ViewType : QueryType.DbsetType;
        }
    }

I have frequently used following implementation.

(I have declared this method in a separate interface which is being implemented by the context class.)

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

If in the case you see it complaining about "Any()" extension method simply stick in "using System.Linq;" if missing.

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