EF 5 复合主键(由于某种原因不起作用)



我知道这可能是一个重复的问题,但我尝试使用类似问题的答案,但我没有任何成功。

情况如下:我正在为一个学校项目创建一个虚拟银行,在第一个原型中,我只需要一个账户表和一个发生业务表。交易和账户之间的关系是每个交易引用两个账户(从和到),账户有0...n个交易。

我一直在使用的代码:

public class Transaction
{
    [Column(Order = 0), Key, ForeignKey("From")]
    public int FromID { get; set; }
    [Column(Order = 1), Key, ForeignKey("To")]
    public int ToID { get; set; }
    public float Amount { get; set; }
    public virtual Account From { get; set; }
    public virtual Account To { get; set; }
}
public class Account
{
    public int ID { get; set; }
    [Required]
    public String Email { get; set; }
    [Required]
    public float Balance { get; set; }
    [InverseProperty("From")]
    public virtual ICollection<Transaction> FromTransactions { get; set; }
    [InverseProperty("To")]
    public virtual ICollection<Transaction> ToTransactions { get; set; }
}

我使用了应该解决问题的[Column(Order = 0)][Column(Order = 1)],但VS仍然显示消息:

Unable to retrieve metadata for 'Bank_API.Models.Account'. Unable to
determine the composite primary key ordering for type
'Bank_API.Models.Transactions'. Use the ColumnAttribute or the HasKey
method to specify an order for composite primary keys.

这是我第一次使用 ASP.NET 或 EF,所以请保持温柔。

附言我使用的是 .NET 4.6.1 和 EF 5。

您的问题是您在交易和帐户中有不同类型的密钥。尝试更改为:

public class Account
{
    public int ID { get; set; }
}

您还可以使Fluent API知道您想要这样的组合键:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     base.OnModelCreating(modelBuilder);
     modelBuilder.Entity<Transaction>().HasKey(x => new { x.FromID, x.ToID });
}

此重写方法应位于 DbContext 类中。此外,属性外键应该在您的虚拟帐户中启动,而不是像您那样的密钥:

public class Transaction
{
    [Column(Order = 0), Key]
    public int FromID { get; set; }
    [Column(Order = 1), Key]
    public int ToID { get; set; }
    public float Amount { get; set; }
    [ForeignKey("FromID")]
    public virtual Account From { get; set; }
    [ForeignKey("ToID")]
    public virtual Account To { get; set; }
}

最新更新