How to store information edited or created in more than 1 entities
In my ASP.net MVC application, i want to store the information, that was edited or created, in several different entities (persons, address, ..).
So my create view exist of input fields for each attributes in persons table and address table. Now I want to store the values in both entities at the same time? Is开发者_StackOverflow this the same approach as with retrieving using a ViewModel? Or is there a better approach ?
You could indeed make your view typed to a view model that encapsulates all the entties you need for that view, but when it's time to store them in the database you'll still have to do it every entity individually, so for example you have:
// here you got hold of your entities already;
// we are in your action method
// this is your context, but please use
// Dependency Injection in your controller ^_^
var context = new dbContext();
context.Add(person);
context.Add(address);
// This will store all the entities you've added in one go.
context.SaveChanges();
SaveChanges()
works as well when you neet do update entities, as long as you retrieve said entities through the same context.
精彩评论