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
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
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