How to check whether DbContext.Set<T> exists in model?
dbcontext, ef-code-first, entity-framework
Solution
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);
}
Problem
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