之前有说过 Code First 重复外键 的一种解决方案。 http://blog.csdn.net/hanjun0612/article/details/50478134
虽然可以解决问题,不过我觉得配置起来非常麻烦,特别时多个表,多个外键的时候。
今天介绍一个简单的方案
数据库表结构:
采用 [InverseProperty("")] 特性来表明外键关系。
实体层:
U1:
public partial class U1 { public U1() { this.Uother = new HashSet<Uother>(); this.Uother1 = new HashSet<Uother>(); } [Key] public int id { get; set; } public string name { get; set; } [InverseProperty("U11")] public virtual ICollection<Uother> Uother { get; set; } [InverseProperty("U21")] public virtual ICollection<Uother> Uother1 { get; set; } }
Uother:
public partial class Uother { [Key] public int id { get; set; } public Nullable<int> u1_id { get; set; } public Nullable<int> u2_id { get; set; } [ForeignKey("u1_id")] public virtual U1 U11 { get; set; } [ForeignKey("u2_id")] public virtual U1 U21 { get; set; } }
-------------------------------------------分割线-------------------------------------------
这里来个复杂一点的,大家不用太关注,
U1
public class U { [Key] public int id { get; set; } public string name { get; set; } } public partial class U1:U { public U1() { this.U2 = new HashSet<U2>(); this.U3 = new HashSet<U3>(); this.U33 = new HashSet<U3>(); } public Nullable<int> input_Qty { get; set; } public Nullable<int> output_Qty { get; set; } [InverseProperty("U1")] public virtual ICollection<U2> U2 { get; set; } [InverseProperty("U12")] public virtual ICollection<U2> U22 { get; set; } [InverseProperty("U1")] public virtual ICollection<U3> U3 { get; set; } [InverseProperty("U12")] public virtual ICollection<U3> U33 { get; set; } }
U2
public partial class U2 { [Key] public int Id { get; set; } public Nullable<int> Uid { get; set; } public Nullable<int> Uid2 { get; set; } public string remark { get; set; } [ForeignKey("Uid")] public virtual U1 U1 { get; set; } [ForeignKey("Uid2")] public virtual U1 U12 { get; set; } }
U3
public partial class U3 { [Key] public int Id { get; set; } public Nullable<int> Uid { get; set; } public Nullable<int> Uid2 { get; set; } public string remark3 { get; set; } [ForeignKey("Uid")] public virtual U1 U1 { get; set; } [ForeignKey("Uid2")] public virtual U1 U12 { get; set; } }
其实也就是如下关系,U2,U3表各有2个外键关联到U1。