基于MVC,EF的基础抽象类的继承和关系

时间:2011-11-02 11:31:00

标签: asp.net-mvc entity-framework inheritance relationship

我有这个示例项目:

型号:

public class Country
{
 public int ID{get; set;}
 public string CountryName{get; set;}
}

public abstract class Subject
{
  public int CountryID{get; set;}
}

public class Person : Subject
{
 public string PersonName{get; set;}
}

public class Company : Subjet
{
 public string CompanyName{get; set;}
}

上下文:

public class SampleContext : DbContext
{
 public DbSet<Contry> Countries{get; set;}
 public DbSet<Person> Persons{get; set;}
 public DbSet<Company> Companies{get; set;}

 modelBuilder.Entity<Person>().Map(m => { m.MapInheritedProperties();ToTable("Person"); });
 modelBuilder.Entity<Company>().Map(m => { m.MapInheritedProperties();ToTable("Company"); });
}

我得到了这个错误。

错误3013:从第xxx行开始映射片段中的问题:缺少表映射:来自表Subject(CountryID)的外键约束Subject_Country

但是,主题是抽象的,我不会在数据库中使用这样的表格。当我在Subject类上使用只有int或string这样的参数时,一切正常。但是当我想在那里使用某些关系时,我得到了这个错误。

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

在SampleContext中,“Country”的名称拼写错误。

public DbSet<Contry> Countries{get; set;} 

应该是:

public DbSet<Country> Countries{get; set;}