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

I have a situation where I can work with several DbContexts, which may or may not contain DbSet SomeEntity.

Naturally, if I run SaveChanges and this object is not present, the following error will occur:

The SomeEntity object type is not part of the model for the current context.

How can I check if an entity or entity exists in the model and short-circuit the code bit if it is not?

Richard

+5
source share
4 answers

An exception should be thrown immediately when you call Set<NotMappedEntityType>, so the easiest way is to catch the exception and handle it as needed.

, , , CLR. , :

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

:

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

EF Core 2.x : NotFound, , DbSetType ViewType, TEntity.

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

.

( , .)

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

If in case you see that it complains about the extension method "Any ()", just insert "using System.Linq;" if absent.

-2
source

All Articles