如何正确更新M:N关系?

时间:2012-07-12 14:33:54

标签: c# model

我在类ThingPeople之间有一个简单的m:m关系,但我在更新记录时的解决方案需要删除以前的记录,然后创建新的

示例:

我的桌子

  • 人(PeopleId,姓名)
  • Thing(ThingId,Name)
  • PeopleHasThing(PeopleId,ThingId)

我的模特

PeopleModel.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关系?

0 个答案:

没有答案