LINQ to SQL and child binding

I am writing a class that (hopefully) allows you to manipulate data through the LINQ to SQL layer, not knowing what individual objects you work with. So far, it works great for cascading selections and inserts, but it's hard for me with updates.

Here is the save method that I use:

if ((long)entity.GetType().GetProperty(GetPrimaryKeyName(entity)).GetValue(entity, null) == 0) { Context.GetTable(entity.GetType()).InsertOnSubmit(entity); } else { Context.GetTable(entity.GetType()).Attach(entity, true); } foreach (PropertyInfo property in entity.GetType().GetProperties()) { if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(EntitySet<>)) { IEnumerable children = (IEnumerable)property.GetValue(entity, null); foreach (object child in children) { Save(child); } } } 

This works until I have a child as part of the update. For example, if I pass in a Customer object with a child Address object that needs to be updated and not inserted as soon as I attach the Customer object, now I have TWO Address objects in my EntitySet โ€” the one I pulled from the database and the new one. Then I get the exception โ€œCan't attach an entity that already existsโ€ when it tries to attach the first child Address object.

Any ideas?

+4
source share
1 answer

Could you attach child entities before you attach the parent? Will this prevent the attachment problem?

Just use reflection to get all EntityRef objects and attach each Entity property to the corresponding table.

+2
source

Source: https://habr.com/ru/post/1286360/


All Articles