私のモデルで CRUD 関係を m:m にする方法は?
例:
マイ テーブル
- 人 (PeopleId、名前)
- モノ (ThingId、名前)
- 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; }
ThingModel.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"
PeopleHasThing:
1, 1 -- ruben has house
1, 3 -- ruben has car
早期アプローチ
PeopleModel.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();
}
}