首页 文章

在EF5.0中映射外键

提问于
浏览
0

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

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

我真正想要的是使用 public virtual Customer Customer {get;set;} 而不是使用Public Int CustID;地址类中的属性...仍然进行映射
作为外键 .

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

2 回答

  • 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);
    
  • 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; }
    }
    

相关问题