在EF5.0中映射外键

时间:2012-09-21 19:36:22

标签: entity-framework c#-4.0 ef-code-first

我将以下表格作为我的实体

public class Customer
{
  public int CustId{get;set;}
  public string Name {get;set;}
}


public class Address
{
  public int Id{get;set;}
  public string Name {get;set;}
   **public virtual Customer Customer {get;set;}**
}

在我使用Fluent API进行地址的模型配置中。我有以下代码

HasKey(p => p.Id);
HasRequired(p => p.Customer).WithMany().Map(m => m.MapKey("CustId"));

我真正想要的不是使用    公共虚拟客户客户{get; set;}   我想拥有Public Int CustID;地址类中的属性...仍然执行映射
   作为外键。

请有人请一些建议......

2 个答案:

答案 0 :(得分:2)

您只需要将属性添加到Address类:

public class Address
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CustId { get; set; }

    public virtual Customer Customer { get; set; }
}

然后更新您的流利,而不是使用.map函数使用.HasForeignKey函数:

        modelBuilder.Entity<Address>()
            .HasRequired(p => p.Customer)
            .WithMany()
            .HasForeignKey(p => p.CustId);

答案 1 :(得分:0)

或者,您可以使用DataAnnotations:

public class Address
{
    [Required, Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public int CustId { get; set; }
    [ForeignKey("CustId")]
    public Customer Customer { get; set; }
}
相关问题