English 中文(简体)
如何检查 DbContext. set <T> 是否存在于模型中?
原标题:How to check whether DbContext.Set<T> exists in model?

我的情况是,我可能与多个DbContexts合作,这些DbContexts可能包含或可能不包含 " 一些实体的DbSet " 。

自然,如果我向SaveChanges开火,而这个实体不在场,就会发生以下错误:

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

如果没有代码,我如何检查该实体或实体是否存在于一个模型和短路中?

理查德·理查德

最佳回答

当您调用 Set< notMappedEntityType> 时, 例外情况应该立即丢弃, 所以最简单的方式是抓取例外并按需要处理 。

复杂的解决方案要求您浏览映射元数据并搜索您的已映射实体类型,该实体类型必须与您的 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);
}
问题回答

EF Core 2.x 更新的扩展方法:如果不存在,返回不着落;如果在模型上界定了实体属性,返回DbSetType或ViewType。

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

这是我的简洁回答:

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

我在执行之后经常使用。

(我已经在一个单独的接口中宣布了这种方法,该接口正在由上下文类别实施。 )

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

如果您看到它抱怨“ 任何( ) ” 扩展方法, 只需粘贴在“ 使用系统. Linq; ” 中, 如果缺少的话 。





相关问题
Entity Framework with MySQL connector in c#

I have been trying to get the Entity Framework to work in my web application using MySQL. It works fine on my local pc, but doesn t work when I put it on the server. Since the server is a shared ...

How Do I Create And Update A Many To Many Relationship With EF

I am using the Entity Framework with SQL Server. I have a many to many relationship between 2 tables. I have created a join table with just the primary key fields of the 2 tables. In the designer, the ...

Entity Framework with File-Based Database

I am in the process of developing a desktop application that needs a database. The application is currently targeted to SQL Express 2005 and works wonderfully. However, I m not crazy about having ...

Linq to enties, insert foreign keys

I am using the ADO entity framework for the first time and am not sure of the best way of inserting db recored that contain foreign keys. this is the code that i am using, I would appreciate any ...

Entity Framework - Many to many question

I have a table called ASB and a table called PeopleInvolved. There is a junction table called PeopleInvolved_ASB which simply contains an ASBID and a PeopleInvolvedID column. The columns act as a ...

Post back complex object from client side

I m using ASP.NET MVC and Entity Framework. I m going to pass a complex entity to the client side and allow the user to modify it, and post it back to the controller. But I don t know how to do that ...

ADO.NET Entity Data Model are not precise enough

I run this code: var cos = from k in _db.klienci_do_trasy where k.klient_id == 5 select k; but the query send to database is: SELECT * FROM `klienci_do_trasy` LIMIT 0, 30 why is it for, there ...

热门标签