开发者

Why TrackableCollection<T> doesn't call the MarkAsDeleted method for removed item?

I have a problem when using the Self-Traking Entities in compination of the WPF.

I have two开发者_如何学C entity set for exmaple: People and Numbers. Each person has many numbers and many numbers can have a person.

Here the sample code which I expect a number deletion:

using (var db = new Model.SampleEntities())
{
    list = db.People.Include("Numbers").ToList();
}

var samplePerson = list[0];
samplePerson.StartTracking();
var number = samplePerson.Numbers.First();
p.Numbers.Remove(number);

using (var db = new Model.SampleEntities())
{
    foreach (Model.Person person in list)
    {
        db.People.ApplyChanges(person);
    }
    db.SaveChanges();
}

It doesn't delete the number from DB.

When I change the TrackableCollection class (Which generated by the Self-Tracking T4 templates) by overriding the RemoveItem method and add the following code, it works as I expected:

protected override void RemoveItem(int index)
{
    var entity = ((IObjectWithChangeTracker)this[index]);
    base.RemoveItem(index);
    entity.MarkAsDeleted();
}

Is it correct to I put the MarkAsDeleted method here? So I should change the TT file to put this code in the TrackableCollection class. Is it a good approach?


No it is not correct. You have many-to-many relation between person and number. You should strictly differ between removing relation (deleting record only from junction table) and between removing item itself and you should not make this automagically because removing number can affect many other persons which you don't work with at the moment (moreover without cascade deletes you will get exception in such case).

If you want to remove relation and delete item call MarkAsDeleted manually. Moreover without bigger effort your change will affect all entities in the model which is not what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜