如何在我的模型中建立 CRUD 关系 m:m?
例子:
我的桌子
- 人员(人员 ID、姓名)
- 事物(事物 ID、名称)
- PeopleHasThing (PeopleId, ThingId)
我的模特
PeopleModel.cs:
public int PeopleId { get; set; }
public string Name
{
get { return _name; }
set
{
if(value == _name) return;
_name = value;
OnPropertyChanged("Name");
}
}
public List<ThingModel> HasThing
{
get { return _hasThing; }
set
{
if(value == _hasThing) return;
_hasThing= value;
OnPropertyChanged("HasThing");
}
}
public static int Insert(PeopleModel m)
{
using (_context = new myDataContext())
{
var d = new People
{
Name = m.Name
Thing = // I don't know how to end this line
};
_context.People.InsertOnSubmit(d);
_context.SubmitChanges();
return d.PeopleId;
}
}
// I don't know how to update or retrieve this from the database
public static void Update(PeopleModel m);
public static void ListAll();
// With this I dont have problem! :P
public static void Delete(int peopleId);
PeopleHasThingModel.cs
public int PeopleId { get; set; }
public int ThingId { get; set; }
事物模型.cs
public int ThingId { get; set; }
public string Name
{
get { return _name; }
set
{
if(value == _name) return;
_name = value;
OnPropertyChanged("Name");
}
}
public bool IsMarked
{
get { return _isMarked; }
set
{
if(value == _isMarked) return;
_isMarked= value;
OnPropertyChanged("IsMarked");
}
}
事物是我表单中的列表是从事物表填充的复选框列表。
例子
我在things
表中有 3 条记录:
1, "house"
2, "dog"
3, "car"
我需要保存一个新的people
和她thing
的:
人们:
1, "ruben"
人有事:
1, 1 -- ruben has house
1, 3 -- ruben has car
早期方法
人模型.cs
public static int Insert(PeopleModel m)
{
using (_context = new myDataContext())
{
var people = new People
{
Name = m.Name
};
// Create the PeopleHasThing record
m.HasThing.ForEach((e) =>
{
people.PeopleHasThing.Add(new PeopleHasThing
{
ThingId = e.ThingId,
People = people
});
});
_context.People.InsertOnSubmit(people);
_context.SubmitChanges();
return people.PeopleId;
}
}
// 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;
//Delete all PeopleHasThings with result.PeopleId ...
EntitySet<PeopleHasThing> set = new EntitySet<PeopleHasThing>();
m.HasThing.ForEach(e =>
{
if (e.IsMarked)
{
set.Add(new PeopleHasThing
{
ThingId = e.ThingId,
People = result
});
}
});
result.PeopleHasThing = set;
_context.SubmitChanges();
}
}