实体类型<type>不是当前上下文模型的一部分 [英] The entity type <type> is not part of the model for the current context

查看:39
本文介绍了实体类型<type>不是当前上下文模型的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进入实体框架,但我不确定我是否遗漏了代码优先方法中的一个关键点.

I am getting into the Entity Framework, but I am unsure if I am missing a critical point in the code-first approach.

我正在使用基于 https://genericunitofworkandrepositories.codeplex.com/ 并创建了我的实体.

I am using a generic repository pattern based on the code from https://genericunitofworkandrepositories.codeplex.com/ and have created my entities.

但是当我尝试访问或修改实体时,我遇到了以下问题:

But when I try to access or modify the entity I run into the following:

System.InvalidOperationException: 实体类型 Estate 不是一部分当前上下文的模型.

System.InvalidOperationException: The entity type Estate is not part of the model for the current context.

当我尝试从我的存储库访问它时会发生这种情况:

It happens when I am trying to access it from my repository:

public virtual void Insert(TEntity entity)
{
    ((IObjectState)entity).ObjectState = ObjectState.Added;
    _dbSet.Attach(entity); // <-- The error occurs here
    _context.SyncObjectState(entity);
}

数据库 (./SQLEXPRESS) 创建得很好,但实体(表)没有在启动时创建.

The database (./SQLEXPRESS) is created just fine, but the entities (tables) is just not created on startup.

我想知道是否需要显式设置实体的映射?EF 自己不能做到这一点吗?

I am wondering if I need to explicit set the mapping of the entities? Is EF not able to this by its own?

我的实体是:

public class Estate : EntityBase
{
    public int EstateId { get; set; }
    public string Name { get; set; }
} 

我的背景是这样的:

public partial class DimensionWebDbContext : DbContextBase // DbContextBase inherits DbContext
{
    public DimensionWebDbContext() :
        base("DimensionWebContext")
    {
        Database.SetInitializer<DimensionWebDbContext>(new CreateDatabaseIfNotExists<DimensionWebDbContext>());
        Configuration.ProxyCreationEnabled = false;
    }

    public new IDbSet<T> Set<T>() where T : class
    {
        return base.Set<T>();
    }

}

出现此错误有什么具体原因吗?我试过在没有任何帮助的情况下启用迁移和自动迁移.

Is there any specific reason why this error occurs? I have tried enable migrations and enable automatic migrations without any help either.

推荐答案

把它放在你的自定义 DbContext 类中:

Put this in your custom DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Estate>().ToTable("Estate");
}

如果您的表不是在启动时创建的,这就是原因.您需要在 OnModelCreating 方法覆盖中告诉 DbContext 有关它们的信息.

If your tables are not created on startup, this is why. You need to tell the DbContext about them in the OnModelCreating method override.

您可以在此处自定义每个实体的映射,也可以将它们分成单独的 EntityTypeConfiguration 类.

You can either do custom per-entity mappings here, or separate them out into separate EntityTypeConfiguration<T> classes.

这篇关于实体类型&lt;type&gt;不是当前上下文模型的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆