好吧,这给了我最终的解决方案--> EF Code 首先,如何实现从一个表到另一个表的两个外键?, NSGaga 感谢您的指导
public class Item : IValidatableObject
{
[Key]
public int ID { get; set; }
public virtual ICollection<ItemRelation> Related{ get; set; }
public string Name { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (....)
{
yield return new ValidationResult("Name not valid", new[] { "Name" });
}
}
}
public class ItemRelation
{
[Key]
public int ID { get; set; }
public int ItemAID { get; set; }
public virtual Item ItemA { get; set; }
public int ItemBID { get; set; }
public virtual Item ItemB { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<ItemRelation>().HasRequired(c => c.ItemA)
.WithMany(m => m.Related)
.HasForeignKey(c => c.ItemAID)
.WillCascadeOnDelete();
modelBuilder.Entity<ItemRelation>().HasRequired(c => c.ItemB)
.WithMany()
.HasForeignKey(c => c.ItemBID)
.WillCascadeOnDelete(false);
}
public DbSet<Item> Items { get; set; }
public DbSet<ItemRelation> ItemsRelations { get; set; }
数据:
Id ItemA_Id ItemB_Id
1 8 2
2 8 3
3 8 5
4 8 5
5 8 5
6 1 6
7 5 4
8 2 9