我正在寻找一种更好的方法来使用Entity Framework更新记录。
以下是我现在使用的内容,其中playerFromModel是从View中获取的数据。
public bool UpdatePlayer(PlayerEntity playerFromModel)
{
bool updateSuccessfull = false;
using (var context = new PlayerEntities())
{
var player = context.Player.Where(m => m.emailAddress == playerFromModel.EmailAddress).FirstOrDefault();
if (player != null)
{
player.emailAddress = playerFromModel.EmailAddress;
player.first_name = playerFromModel.FirstName;
player.last_name = playerFromModel.LastName;
player.alt_email_id1 = playerFromModel.AlternateEmailAddress;
player.street = playerFromModel.Street;
player.city = playerFromModel.City;
player.state = playerFromModel.State;
player.zip = playerFromModel.Zip;
player.country_code = playerFromModel.CountryCode;
player.phone1 = playerFromModel.Phone;
try
{
context.SaveChanges();
updateSuccessfull = true;
}
catch
{
updateSuccessfull = false;
}
}
}
return updateSuccessfull;
}
正如您所看到的,我必须手动映射每个字段以及我在任何地方都遵循的相同方法。
我当时认为必须有更好的方法来做到这一点。
请指导我。感谢。
答案 0 :(得分:5)
您可以使用TryUpdateModel。 e.g。
bool updateSuccessfull = false;
using (var context = new PlayerEntities())
{
var player = context.Player.Where(m => m.emailAddress == playerFromModel.EmailAddress).FirstOrDefault();
if (player != null)
{
//Beware this will try to map anything it can. This can be dangerous
if(TryUpdateModel(player)){
try
{
context.SaveChanges();
updateSuccessfull = true;
}
catch
{
updateSuccessfull = false;
}
}
}
}
return updateSuccessfull;
}
我不会在这里看到Real example of TryUpdateModel, ASP .NET MVC 3。
你可以使用Automapper或MiBu所说的类似的东西。创建播放器的ViewModel link is here,然后从中映射到实体
//Get a PlayerUpdate ViewModel
using (var context = new PlayerEntities())
{
// fetch the domain model that we want to update - BTW I'd use a repository pattern but that is another debate
var player = context.Player.Where(m => m.emailAddress == playerFromModel.EmailAddress).FirstOrDefault();
if (player != null)
{
// Use AutoMapper to update only the properties of this domain model
// that are also part of the view model and leave the other properties unchanged
AutoMapper.Map<UpdatePlayerViewModel , PlayerEntity>(viewModel, player);
try
{
context.SaveChanges();
updateSuccessfull = true;
}
catch
{
updateSuccessfull = false;
}
}
但是我认为更新实体属性是一件重要的事情,不应该自动完成。其他人也有同感。创建AutoMapper的Jimmy Bogard似乎并不认为它需要two way mapping(但他说这部分是因为他们根据他们的要求构建了AutoMapper)这里的类似答案on Stackoverflow说自己动手。
这取决于应用程序的复杂性,但我会查看使用命令模式将消息发送到包含您的属性的适当处理程序并让处理程序更新它们。如果它成功了我们做一件事,如果不是我们做另一件事。 MVC in Action中描述了相同的模式。请参阅类似内容(此处为链接)[http://www.paulstovell.com/clean-aspnet-mvc-controllers]和此处is the second link