Mathieu
Mathieu

Reputation: 4520

Best way of handling views

I want to start that new project with the best practice possible. I have a lot of tables that are linked together. Example:

Person
- ID
- FirstName
- LastName

User
- ID
- PersonID
- AddressID

Address
- ID
- Line1
- Line2

Obviously, I will have to use a UserView view to be efficient in the application. The view will bring these three tables together.

Now, when someone makes a change to a user, I will have to query all three tables individually, make the changes and then update.

private void updateUser(UserView userView)
{
   using (var context = getNewContext()
   {
      var person = context.Person.first(c => c.ID == userView.PersonID)
      person.FirstName = userView.FirstName;
      person.LastName = userView.LastName;
      context.SaveChanges();

      var user = context.User.first(c => c.ID == userView.UserID)
      //and so on for the 3 tables
   }
}

There has to be a more efficient way of updating the tables! Do you know any trick?

Upvotes: 1

Views: 63

Answers (1)

Andreas
Andreas

Reputation: 6475

I assume you're using the entity framework. If you've got navigation properties you can eagerly load your object graph in one trip to the database, update the fields and then save it.

var user = context.User.Include("Person").Include("Address").First(c => c.ID == userView.UserID);
user.Person.FirstName = userView.FirstName;
user.Person.LastName = userView.LastName;
user.Address... // etc.

If you're using Linq2Sql, you've got to use DataLoadOptions. There's a blog post explaining the difference between EF and Linq2Sql.

Upvotes: 1

Related Questions