我有一个Item表,它本身有manyTomany:
public virtual ICollection<Item> Related { get; set; }
modelBuilder.Entity<Item>().HasMany(x => x.Related ).WithMany();数据:
Item_Id Item_Id1
8 2
8 3
8 4我如何才能允许重复,也就是允许另一个8-2。例如,当我尝试插入另一个“重复”数据时,它只显示1。
发布于 2013-04-14 18:09:50
这给了我最终的解决方案--> EF Code First, how can I achieve two foreign keys from one table to other table?,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发布于 2014-06-13 01:19:31
我认为问题的根源是误解了什么是实体。实体是唯一的,并且具有唯一的Id,因此,例如,一家公司可以有一个受雇人员的集合,这些集合是唯一的,因此在同一集合中不能有同一个人的两个实例。如果你有购物车,你必须将集合中的项目视为“订单行”,而不是项目本身。任何订单行都有自己的Id和对实体的引用,即您要购买的对象。
发布于 2013-04-14 02:46:14
我没有特别检查,所以你可能需要弄清楚细节-
但是(我认为)唯一的方法是对索引表(例如Item2Item)执行索引表。
查看我为附加信息EF code-first many-to-many with additional data制作的这篇文章,它是关于如何为多对多创建自定义表-添加附加字段。
现在您有了一个定制表,您需要对它进行一些修改-您需要从.HasKey中删除组合键。改为使用您自己的pk,例如,任何其他表的身份。
也就是说,您可以定义一个唯一的PK,就像任何其他表一样-并将其作为您的键。这将使您在fk列中具有重复的键)。
检查这篇文章,因为它似乎在逻辑上接近(尽管不是相同的)
Many to many (join table) relationship with the same entity with codefirst or fluent API?
https://stackoverflow.com/questions/15991279
复制相似问题