有三个实体:
public class TAs
{
public string ID { get; set; }
public string Name { get; set; }
public virtual ICollection<TCs> TCs { get; set; }
}
public class TBs
{
public string ID { get; set; }
public string Name { get; set; }
public virtual ICollection<TCs> TCs { get; set; }
}
public class TCs
{
public string TBId { get; set; }
public string TAId { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> Birthday { get; set; }
public virtual TAs TAs { get; set; }
public virtual TBs TBs { get; set; }
}
要在数据库中生成如下图的表,该如何实现?
其中TCs中的TBId,TAId为TAs,TBs的外键同时也为自己的主键
TCs
1 public class TCs 2 { 3 [Key, Column(Order = 0)] 4 public string TBId { get; set; } 5 [Key, Column(Order = 1)] 6 public string TAId { get; set; } 7 public string Name { get; set; } 8 public Nullable<System.DateTime> Birthday { get; set; } 9 10 [ForeignKey("TAId")] 11 public virtual TAs TAs { get; set; } 12 13 [ForeignKey("TBId")] 14 public virtual TBs TBs { get; set; } 15 }
TAs
1 public class TAs 2 { 3 [KeyAttribute] 4 public string ID { get; set; } 5 public string Name { get; set; } 6 7 public virtual ICollection<TCs> TCs { get; set; } 8 }
TBs
1 public class TBs 2 { 3 [KeyAttribute] 4 public string ID { get; set; } 5 public string Name { get; set; } 6 7 public virtual ICollection<TCs> TCs { get; set; } 8 }
你这种方法也行,但我后来找到了更简洁的办法:
public class TCConfiguration : EntityTypeConfiguration<TC>
{
public TCConfiguration()
{
HasKey(m => new { m.TAID, m.TBID });
HasRequired(o => o.TA).WithMany(o => o.TC).HasForeignKey(o => o.TAID);
HasRequired(o => o.TB).WithMany(o => o.TC).HasForeignKey(o => o.TBID);
}
}
你这个也能够解决问题,那豆豆还是给你拉
你这种方法也行,但我后来找到了更简洁的办法,TC加个TAID,TBID,其他的不要用Attribute去修饰了
public class TCConfiguration : EntityTypeConfiguration<TC>
{
public TCConfiguration()
{
HasKey(m => new { m.TAID, m.TBID });
HasRequired(o => o.TA).WithMany(o => o.TC).HasForeignKey(o => o.TAID);
HasRequired(o => o.TB).WithMany(o => o.TC).HasForeignKey(o => o.TBID);
}
}
你这个也能够解决问题,那豆豆还是给你拉