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?
Brian
source share