2017-06-01 98 views
-1

我有以下两个2个车型在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)&客户ID(CustId)。虽然Account可以由源系统(SrcSys),客户ID(CustId)加上帐户Id(AccId)标识。但第二种模式不允许我使用另一个列。

请查看您的专家是否有帮助。

Thanx提前。

+0

什么是错误消息? – CodeNotFound

+0

在外键行处重复“列”属性,列中有下划线, – InAction

回答

2

我发现指定复合键(包括PK和FK)更容易理解和更少的错误使用流利的API配置容易:

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; } 
} 
+0

感谢Ivan,但是,如果我错了,请纠正我,我猜你在数据注释代码中忘记注释掉两个早期的ForeignKey行不正确地插入,单行复合键就足够了。 – InAction

+0

对于数据注释 - 是的,我已经纠正了这一点。对于流畅的API - 您必须定义“一对多”关系配置,以便获得“HasForeignKey”方法。 –