Save username in MVC2 + EF4

I am working on a simple MVC2 project with EF4. I also use the repository template that is created in the controller constructor. I have 34 tables with the BuiltBy and LastModifiedBy fields that need to be populated when the record is saved.

Do you have other ideas on how to pass the username from an entity controller 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();
}
+3
source share
2 answers

You can create a custom mediator that sets these two properties before the action is called.

Something like that:

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);
        }
    }
+1
source

. , ( hiearchy).

, :

// 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;
     ...
  }
}

, IIdentity , . - HttpContext.

+1

Source: https://habr.com/ru/post/1794034/


All Articles