【发布时间】:2018-07-22 16:42:36
【问题描述】:
定义多对多关系不是问题。
我有一个 Rooms 表(就像房子里的房间),每一个都可以有 Colors 表中的一种或多种颜色。
每个都有一个对相反表的 List 引用 - 请参阅下面的类。
在 Configuration 类的 Seed 方法中,我正在使用 AddOrUpdate 创建各种表。
ctx.Rooms.AddOrUpdate(r => new { r.Name, r.HouseId },
new Room
{
Name = "Kitchen",
House = (from h in ctx.Houses where h.Address == "Littleton, MA" select h).First(),
HouseId = (from h in ctx.Houses where h.Address == "Littleton, MA" select h.HouseId).First()
});
(当然是 ctx.SaveChanges)
而且我可以用同样的方式创建多种颜色:
ctx.Colors.AddOrUpdate(c => new { c.ColorName },
new Color
{
ColorName = "Green"
});
我想为每个房间关联一种或多种颜色。
EF 创建一个以多对多关系关联两者的表。
看起来这应该很容易,但我找不到方法,我也搜索了网络。 谢谢你的帮助。 :-)
【问题讨论】:
-
我没有看到任何问题?
-
嗨,大声笑,很抱歉...首先,我尝试使用 AddOrUpdate 为 Room 播种并指定其颜色。其次,我正在尝试使用 linq 来创建房间并指定与之关联的颜色。
-
Room.Colors.Add(颜色颜色)。确保在 Room 构造函数中初始化列表。
-
将此作为建议的答案发布,以便我检查并非常感谢您
标签: entity-framework many-to-many seed