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

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

问题描述

我进入实体框架,但我不能确定,如果我缺少在code-第一种方法的一个关键点。

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

我使用基于从code <一个通用存储库模式href=\"https://genericunitofworkandrepositories.$c$cplex.com/\">https://genericunitofworkandrepositories.$c$cplex.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:实体型地产是不是一部分
  的型号为当前上下文。

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

数据库(./SQLEX$p$pSS)创建就好了,但只是没有在启动时创建的实体(表)。

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

我的环境是如此:

My context is as so:

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 类:

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

如果在启动时不创建您的表,这是为什么。你需要告诉的DbContext关于他们在OnModelCreating方法重写。

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&LT; T&GT;

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

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

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