我在类之间有一个简单的关系 m:m Thing
,People
但是我的解决方案在更新记录时需要删除以前的记录,然后创建新的记录
例子:
我的桌子
- 人员(人员 ID、姓名)
- 事物(事物 ID、名称)
- PeopleHasThing (PeopleId, ThingId)
我的模特
人模型.cs
// The following method works!
// I've tried but I have my doubts about deleting records
public static void Update(PeopleModel p)
{
using (_context = new myDataContext())
{
var result = (from r in _context.People
where r.PeopleId == p.PeopleId
select r).SingleOrDefault();
if (null == result) return;
result.Name = p.Name;
PeopleHasThing.DeleteAllByPeopleId(result.PeopleId);
EntitySet<PeopleHasThing> set = new EntitySet<PeopleHasThing>();
//HasThing = List<ThingModel>
//ThingModel: { (Int32)ThingId, (bool)IsMarked. (string)Description }
m.HasThing.ForEach(e =>
{
if (e.IsMarked)
{
set.Add(new PeopleHasThing
{
ThingId = e.ThingId,
People = result
});
}
});
result.PeopleHasThing = set;
_context.SubmitChanges();
}
}
啊,问题是如何正确更新 M:N 关系?