问题
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
回答1:
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);
}
回答2:
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);
}
}
回答3:
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;
}
}
回答4:
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.
来源:https://stackoverflow.com/questions/10749307/how-to-check-whether-dbcontext-sett-exists-in-model