views:

44

answers:

1

Okay, I've been struggling with this for a while now.

I have a standard MVC2 project and use EF4 to access data objects. Many of my data objects (and therefore database tables) have two common fields: UpdateUserAccountID and UpdateDate.

In each of my controllers, I am currently setting this fields manually within each controller on the Edit action:

    // POST: /Modes/Edit/2
    [HttpPost]
    public ActionResult Edit(int id, FormCollection formValues)
    {
        Mode mode = _repository.GetMode(id);

        //Set update flags
        mode.UpdateUserAccountID = _userRepository.GetUserID(User.Identity.Name);
        mode.UpdateDate = DateTime.Now;

        try
        {
             UpdateModel(mode);
             _repository.Save();
             return RedirectToAction("Details", new { id = mode.ModeID });
         }
         catch
         {
             return View(mode);
         }

    }

Problem is, I want to update these two fields in a central place, regardless of the type of the controller. I am using Repository/IRepository pattern for my data objects. I also have set up a BaseController as I thought I could pass in my 'mode' object in the example above to a generic function in a base controller to set these two fields. But, I couldn't figure that out and the generic function has no awareness of these specific fields.

Should I be creating a base class for my repositories instead? I can't envisage how that would work within the MVC framework. In webforms, I would just have had an interface that all my models implement with the common fields but i can't seem to fit it in to an MVC approach.

Any help as to the approach to take would be great.

+1  A: 

This post contains a detailed solution for this scenario: Entity Framework - Auditing Activity

Basically, the idea is how to update common properties like LastModifiedBy or LastModifiedDate on all entities before they saved on the data store at the EF data access layer with one common code.

You should get rid of the 2 lines of codes where you Set update flags and let that all happens in the Context_SavingChanges() like the way it has been described in the above link. Since you are in a web scenario, you have to pass User.Identity.Name back to your Repository.Save() method and then invoke Repository.GetUserID() on the Context_SavingChanges() as well.

This way, you don't need to update these 2 properties each and every time you insert or update an entity to the data store. It will automatically all happens in one place just before saving.

Morteza Manavi
This solution worked perfectly. Thanks A lot!
Thomas
You are very welcome, I'm glad it helped :)
Morteza Manavi