问题描述
- EF一对多,插入子集时怎么设置父级的ID?
-
两张表如下,我现在要插入AroundGoods,需要指定AroundShop,但是怎么指定AroundShop的ID?public class AroundShop : ShopBase { public UserInfo User { get; set; } public virtual ICollection<AroundGoods> GoodsList { get; set; } } public class AroundGoods : GoodsBase { public AroundShop Shop { get; set; } } public class AroundShopfiguration : EntityTypeConfiguration<AroundShop> { public AroundShopfiguration() { HasMany(d => d.GoodsList).WithRequired(l => l.Shop); } } //我现在这样写就查找不到shop List<AroundGoods> list = new List<AroundGoods>(); for (int i = 0; i < 50; i++) { list.Add(new AroundGoods { GoodsName = "瓜子" + (i + 1), GoodsPrice = 5 + new Random().Next(0, 4), GoodsIntroduce = "good", GoodsImg = imgarr[i > 24 ? i - 25 : i], Shop = new AroundShop { Id = new Guid("B8A98A53-04FA-E411-BD4C-A9F0B66714A5") } }); } db.AroundGoods.AddRange(list); db.SaveChanges();
解决方案
既然是一对多,直接AroundShop.Single(x => x.id == 父id).GoodsList.AddRange(list);
就可以了。
时间: 2024-11-01 19:10:16