Reputation: 115
Ive been trying to solve a problem for sometime and can't seem to find anything that works...
In my MVC application I receive an address object with a comma separated string of names which are associated to it. e.g:
public class address
{
public string Names { get; set; } //-- "Name-One,Name-Two,Name-Three"
}
In my service layer I split this list into a string array.
Now using entity Framework i need to preform three tasks
1) Create new Name objects to be stored in the database and add them to the address.
2) Delete old name objects from the database and remove them from the address.
3) Commit the changes so the address object is linked to new multiple list of name objects.
Has anyone got any ideas how this can be without hitting the database to much. (avoiding endless for each loops)
Thanks in advance
Jay
Upvotes: 0
Views: 2253
Reputation: 47375
string[] newNames = ServiceLayerSplitCommaSeparatedIntoArray(addressObj);
var entity = dbContext.Set<Address>().Find(addressId);
entity.Names.Clear();
foreach (var newName in newNames)
entity.Names.Add(new AddressName {
Value = newName,
});
dbContext.SaveChanges();
I think the most efficient way to do this is to complete your tasks as 2, then 1, then 3.
The entity.Names.Clear()
line will remove all old Name objects from the address. As long as those entities have a required foreign key to the address entity, they will also be deleted from the database. Otherwise, if they have an optional foreign key, you can do this to delete them from the database (instead of Clear
on the Names
collection):
var oldNames = entity.Names.ToArray();
foreach (var oldName in oldNames)
dbContext.Set<AddressName>().Remove(oldName);
//entity.Names.Clear(); // Remove calls above will clear these automatically
You can then iterate over your string array and add the new entities to the collection.
Finally, save the changes. Everything will be deleted and added in a single database roundtrip.
Upvotes: 2