【问题标题】:Entity framework - Invalid Object Name实体框架 - 无效的对象名称
【发布时间】:2012-02-20 19:41:08
【问题描述】:

我有一个使用 EF 4.1 的项目。

在数据上下文中:

 public DbSet<Customer> Customer { get; set; }       
 protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)      {            }

实体模型类:

[Table("User",SchemaName="dbo")]
public class User{  
public int Id { get; set; }  
public string FirstName { get; set; }  
public string LastName { get; set; } 
}

运行应用程序后,出现以下错误。

无效的对象名称 dbo.User

为什么?怎么了?

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    您的 OnModelCreating 方法中有什么?

    尝试删除默认的复数表名:

    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    

    【讨论】:

      【解决方案2】:

      如果您碰巧使用配置映射 (EntityTypeConfiguration) 类来定义您的表,如果您忘记将表的配置类附加到模型生成器,您将收到此错误。

      就我而言,它确实让我有点难过,因为我已经有另一个表 (SomeThing) 在这个 Context 类中完美运行。在简单地添加一个新表 (OtherThing) 之后,似乎 的所有设置都与第一个相同,我得到了错误:Invalid object name 'dbo.OtherThings

      答案在我的 Context 类中:

      public DbSet<SomeThing> SomeThings { get; set; }
      public DbSet<OtherThing> OtherThings { get; set; }
      
      ...
      
      protected override void OnModelCreating(DbModelBuilder modelBuilder)
      {
          modelBuilder.Configurations.Add(new SomeThingMap());
      
          // OOPS -- Forgot to add this!!
          modelBuilder.Configurations.Add(new OtherThingMap());
      }
      

      作为参考,这是我的SomeThingMap 课程:

      public class SomeThingMap : EntityTypeConfiguration<SomeThing>
      {
          public SomeThingMap()
          {
              ...
      
              this.ToTable("SomeThing");
      
              ...
          }
      }
      

      还有我的新OtherThingMap 班级:

      public class OtherThingMap : EntityTypeConfiguration<OtherThing>
      {
          public OtherThingMap()
          {
              ...
      
              this.ToTable("OtherThing");
      
              ...
          }
      }
      

      这是一个长远的目标,但我希望这至少可以帮助其他人指出正确的方向。

      【讨论】:

      • 我尝试使用ToTable 和注释均未成功,但我仍然不断收到此错误。有关更多信息,请查看我的post
      • 添加架构名称 like -> this.ToTable("TableName", "SchemaName")
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多