I have a situation where I may be working with multiple DbContexts that may or may not contain a DbSet of SomeEntity.
Naturally, if I fire off SaveChanges and this entity is not present, the following error will occur:
The entity type SomeEntity is not part of the model for the current context.
How can I check whether the entity or entity set exists in a model and short-circuit the offending bit of code if it does not?
Richard
DbContext.SaveChanges Method (Microsoft.EntityFrameworkCore) Saves all changes made in this context to the database. This method will automatically call DetectChanges() to discover any changes to entity instances before saving to the underlying database.
The DbContext class is an integral part of Entity Framework. An instance of DbContext represents a session with the database which can be used to query and save instances of your entities to a database. DbContext is a combination of the Unit Of Work and Repository patterns.
A DbContext instance represents a combination of the Unit Of Work and Repository patterns such that it can be used to query from a database and group together changes that will then be written back to the store as a unit. DbContext is conceptually similar to ObjectContext.
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);
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With