for example, i have a data table named [User], and mapping to User enetity with EF4:
Id, FullName, EmailAddress, Fax, Tel
in the web page, i just only want to update the "EmailAddess" and "Fax" 2 properties below:
@using (Html.BeginForm("Edit", "User"))
{
<label>Email Address:</label>
@Html.TextBox("EmailAddress")
<label>Fax:</label>
@Html.TextBox("Fax")
<input type="submit" value="Update" />
}
and controller i did for this:
public ActionResult Edit(User user) {
var _user = GetUsers().Where(a => a.Id == user.Id).SingleOrDefault();
_user.Fax = user.Fax;
_user.EmailAddress = user.EmailAddress;
context.SaveChanges();
}
yes, i updated it and successful, but next time i also want to update "Tel", so i need to change the code like this:
_user.Fax = user.Fax;
_user.EmailAddress = user.EmailAddress;
_user.Tel = user.Tel;
if i have 100 fields, i will be crazy for doing it :(
So, how can i only update the models to d开发者_JAVA技巧atabase for related fields in web page?
thanks
You should definitely look into AutoMapper ( http://automapper.codeplex.com/ ).
AutoMapper.Mapper.CreateMap(typeof(User), typeof(UserViewModel));
AutoMapper.Mapper.CreateMap<User, UserViewModel>()
.ForMember(d => d.Property1, f => f.MapFrom(s => s.Property1))
.ForMember(d => d.Property2, f => f.MapFrom(s => s.Property2))
.ForMember(d => d.Property3, f => f.MapFrom(s => s.Property3));
Then in your Edit you can do the following
public ActionResult Edit(User user) {
var _user = GetUsers().Where(a => a.Id == user.Id).SingleOrDefault();
AutoMapper.Mapper.Map(user, _user);
context.SaveChanges();
}
Entity framework will only update the fields that have actually changed.
Pretty sure that's about all you need.
精彩评论