开发者

Saving the username in MVC2 + EF4

I am working on a simple MVC2 project with EF4. I am also using Repository pattern which is instantiated in the controller's constructor. I have 34 tables each with CreatedBy and LastModifiedBy fields that needs to populated when the record is saved.

Do you have other ideas on how to pass the username from th开发者_如何学Goe controller to the entity other than this:

[HttpPost]
public ActionResult Create(){

     Record rec = new Record();
     TryUpdateModel(rec);
     rec.CreatedBy = HttpContext.Current.User.Identity.Name;
     rec.LastModifiedBy = HttpContext.Current.User.Identity.Name; 
     repository.Save();

     return View();
}


You can create custom model binder that would set these two properties before action gets invoked.

Something like this:

public class CustomModelBinder : DefaultModelBinder
    {
        protected override void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor)
        {
            if ((propertyDescriptor.Name == "CreatedBy") || (propertyDescriptor.Name == "LastModifiedBy"))
            {
                //set value
            }
            base.BindProperty(controllerContext, bindingContext, propertyDescriptor);
        }
    }


You can wrap this in repository. If all your entities share same fields you can define bass entity with those fields and derive other entities from this one (Table per concrete class hiearchy).

Then you can define base class for your repository like:

// Other repositories derive from this repository
// BaseEntity is parent of all your entities and it has your shared fields
public abstract class BaseRepository<T> where T : BaseEntity
{
  ....
  public void Save(IIdentity user, T entity)
  {
     entity.CreatedBy = user.Name;
     entity.LastModifiedBy = user.Name;
     ...
  }
}

You can further improve this code by passing IIdentity directly to repository constructor or better by passing some custom Identity provider to repository constructor. Default provider implementation for web application will return identity from HttpContext.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜