实体框架/ MVC4 - 与多列密钥的关系

时间:2013-01-24 22:10:42

标签: entity-framework asp.net-mvc-4

我是EF的新手,我很难找到如何在我的主表投资者与联系信息之间建立关系,以及可以为每个投资者提供许多笔记的表格。以下是模型:

public class Investor
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Company { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Cell { get; set; }
    public string Fax { get; set; }
    [Display(Name="Address 1")]
    public string Address1 { get; set; }
    [Display(Name = "Address 2")]
    public string Address2 { get; set; }
    public string City { get; set; }
    [StringLength(2, ErrorMessage = "State must be 2 characters")]
    public string State { get; set; }
    public string Zip { get; set; }
    public string ContactTableId { get; set; }
    [ForeignKey("ContactTableId, ContactId")]
    public virtual List<Note> Notes { get; set; }
}

public class Note
{
    [Key]
    [Column(Order = 0)]
    public string ContactTableId { get; set; }
    [Key]
    [Column(Order = 1)]
    public int? ContactId { get; set; }
    public string note { get; set; }
    public DateTime? DateCreated { get; set; }
}

如上所述,我尝试设置它会产生错误'关系约束中从属和主要角色中的属性数必须相同。'在声明中:

public ActionResult Index()
{
    return View(db.Investors.ToList());
}

在控制器中。如何设置它以使其自动拉出Notes。

1 个答案:

答案 0 :(得分:0)

外键不是&#34; ContactTableId,ContactId&#34;,它是表Investor_Id(或Notes)中的单个字段Note。 EF认为你试图将单个键映射到两个字段并硬币这个有点难以捉摸的异常消息。但只需删除ForeignKey属性,EF就会使用Note中的外键字段。