我在MVC项目中有两个以下两个模型:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace RiskDotNet.Models
{
public class Customer
{
[Key, Column(Order = 0)]
public string SrcSys { get; set; }
[Key, Column(Order = 1)]
public string CustId { get; set; }
public string CustNm { get; set; }
public virtual ICollection<Account> Accounts { get; set; }
}
}
和
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace RiskDotNet.Models
{
public class Account
{
[Key, Column(Order = 0)]
[ForeignKey("Customer"), Column(Order = 0)]
public string SrcSys { get; set; }
[Key, Column(Order = 1)]
[ForeignKey("Customer"), Column(Order = 1)]
public string CustId { get; set; }
[Key, Column(Order = 2)]
public string AccId { get; set; }
public string BrId { get; set; }
public string ProdId { get; set; }
public virtual ICollection<Balance> Balances { get; set; }
public virtual Customer Customers { get; set; }
}
}
Customer
可由复合密钥源系统(SrcSys
)&amp;客户ID(CustId
)。虽然可以通过源系统(Account
),客户ID(SrcSys
)以及帐户ID(CustId
)识别AccId
。但第二个模型不允许我使用另一个专栏。
请查看您是否有专家可以提供帮助。
提前完成。
答案 0 :(得分:2)
通过使用流畅的API配置,我发现指定复合键(PK和FK)更容易理解,并且更不容易出错:
modelBuilder.Entity<Account>()
.HasRequired(e => e.Customers) // the property should really be called Customer, currently it sounds like collection
.WithMany(e => e.Accounts)
.HasForeignKey(e => new { e.SrcSys, e.CustId }); // <= the composite FK
但如果您更喜欢数据注释,只需在导航属性上应用ForeignKey
属性,并提供带有FK属性名称的逗号分隔列表:
public class Account
{
[Key, Column(Order = 0)]
public string SrcSys { get; set; }
[Key, Column(Order = 1)]
public string CustId { get; set; }
[Key, Column(Order = 2)]
public string AccId { get; set; }
public string BrId { get; set; }
public string ProdId { get; set; }
public virtual ICollection<Balance> Balances { get; set; }
[ForeignKey("SrcSys,CustId")] // <= the composite FK
public virtual Customer Customers { get; set; }
}