EntityFramework ComplexType引用EntityType

时间:2015-06-01 15:17:43

标签: c# entity-framework

我对EntityFramework的Code First方法很陌生,当我尝试创建引用实体类型的可重用复杂类型时,我收到以下错误。

型号:

 class Bank
{
    public int Code { get; set; }
    public string Name { get; set; }
}
 class BankAccount
{
    public Bank Bank { get; set; }
    public int BankId { get; set; }
    public int Agency { get; set; }
    public int Account { get; set; }

}
 class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public DateTime BirthDate { get; set; }
    public BankAccount BankAccount { get; set; }
}

的DbContext:

class DemoContext : DbContext
{

    public DbSet<Bank> Banks { get; set; }
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<Bank>().HasKey(b => b.Code);
        modelBuilder.ComplexType<BankAccount>();

    }

}

当我尝试添加迁移时,出现以下错误:

One or more validation errors were detected during model generation:

ComplexTypeProblem.EF.Bank: Name: Each type name in a schema must be unique. Type name 'Bank' is already defined.
ComplexTypeProblem.EF.Bank: : EntityType 'Bank' has no key defined. Define the key for this EntityType.
Banks: EntityType: EntitySet 'Banks' is based on type 'Bank' that has no keys defined.

是否有任何警告要实现这种关系,其中ComplexType具有EntityType的导航属性?

由于

2 个答案:

答案 0 :(得分:1)

您不能拥有包含 EntityType ComplexType 。只是相反。

ComplexTypes 只是实体的属性,它们应该像普通字段一样处理您的代码。

答案 1 :(得分:1)

您是否尝试设置1 - &gt;银行/银行账户的许多映射?如果是这样,我会建议如下:

public partial class Bank
{
  public Bank()
  {
    BankAccounts = new List<BankAccount>();
  }

  public int Code { get; set;}
  public string Name { get; set;}

  public virtual ICollection<BankAccount> BankAccounts { get; set;}
}
public partial class BankAccount
{
  public int BankId { get; set;}
  public int Agency { get; set;}
  public int Account { get; set;}

  public virtual Bank Bank { get; set;}
}

并按如下方式更改OnModelCreating方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Bank>().HasKey(b => b.Code);
    modelBuilder.Entity<Bank>().HasMany(m => m.BankAccounts).WithRequired(r => r.Bank).HasForeignKey(f => f.BankId).WillCascadeOnDelete(false);
}