Update database n:n
I have two classes:
public class RichMan
{
public string ID {get;set;}
List<Car> _cars=new List<Car>();
{
public List<Car> Cars
{开发者_JAVA百科
get
{
return this._cars;
}
set
{
this._cars = value;
NotifyChanged("Email");
}
}
}
and
public class Car
{
public string ID {get;set;}
}
And 3 tables:
RichMan
ID int
Cars:
ID int
and CarsOfRichmen
idcar int (FK)
idrichman (FK)
If collection of cars of richamn would change how to do it on database ?
Delete all records from CarsOfRichmen where idrichman is id of my richam, and then in foreach add realtions to CarsOfRichmen ?
Is it good practice ?
No, it's not a good practice.
Cars can have other linked information; changes in Cars can trigger other actions.
You must just Add/Delete/Update relevant cars [EDIT] and/or CarsOfRichmen...
There are at least 3 patterns I know of here:
1) As per Pascal - analyze the 'before' and after scenarios and then apply the relevant delta to the data (insert, update and delete) of the links as needed.
2) Deleting the links as you suggested (but not the Cars) is quite a common pattern. You should however have some form of logging / audit capability so that you can recreate what happened.
3) The other common pattern is to add a date from / date to range on the links and version them this way. Performance can however be degraded as the links stack up quite rapidly.
精彩评论