2012-02-20 75 views
2

我有一个项目,我使用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

为什么?哪里不对?

回答

2

你的OnModelCreating方法是什么?

尝试删除默认的复数表名:如果你碰巧使用的配置映射(EntityTypeConfiguration)类来定义你的表

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); 
+0

谢谢,达娜。它的工作原理 – 2012-02-20 19:49:36

0

,因此当你忘记附上配置类得到这个错误对于模型构建器的表格。

在我的情况下,它真的让我困惑了一下,因为我已经有另一个表(SomeThing)在这个Context类中完美地工作了。在简单地添加一个新表(OtherThing),其中一切似乎设置为与第一个相同,我得到了错误:Invalid object name 'dbo.OtherThings

的答案是我的上下文类:

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

     ... 
    } 
} 

这是一个漫长但我希望这有助于指出其他人正确的方向,a至少。

+0

您使用的是Unity吗? – JoshYates1980 2015-05-13 13:24:51

相关问题