可以反过来使用实体框架方法DbPropertyValues.SetValues来设置对象的值,即视图模型或数据传输对象,基于实体中属性的当前值吗?
这是我如何将SetValues与DTO一起使用以仅更新我在DTO的类定义中指定的属性的一个示例。
public Address UpdateAddress(Address address)
{
using (var context = new OrdersContext())
{
var targetAddress = context.Addresses.FirstOrDefault(a => a.AddressID == address.AddressID && a.User.UserName.ToLower() == HttpContext.Current.User.Identity.Name.ToLower());
if (targetAddress == null) return null; // Address not found or user doesn't own this address.
context.Entry(targetAddress).CurrentValues.SetValues(address);
context.SaveChanges();
return new Address
{
AddressID = targetAddress.AddressID,
AddressLine1 = targetAddress.AddressLine1,
AddressLine2 = targetAddress.AddressLine2,
City = targetAddress.City,
State = targetAddress.State,
ZipCode = targetAddress.ZipCode
};
}
}
public class Address
{
public int AddressID { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
// public string UserID { get; set; } // UserID is excluded from the view model so that it cannot be updated.
}
正如SetValues上的文件所示
给定对象可以是任何类型。对象上的任何属性都带有 与字典中的属性名称匹配且可以读取的名称, 将被阅读。其他属性将被忽略。这允许复制 简单数据传输对象(DTO)的属性。
可以反向使用SetValues来设置实体的DTO值,以便不必逐个手动设置值吗?或者是否有另一种方法可以像SetValues一样工作但反过来?
还有另一个DbPropertyValues method called ToObject,但它不适用于DTO。
我想做这样的事情:
public Address UpdateAddress(Address address)
{
using (var context = new OrdersContext())
{
var targetAddress = context.Addresses.FirstOrDefault(a => a.AddressID == address.AddressID && a.User.UserName.ToLower() == HttpContext.Current.User.Identity.Name.ToLower());
if (targetAddress == null) return null; // Address not found or user doesn't own this address.
context.Entry(targetAddress).CurrentValues.SetValues(address);
context.SaveChanges();
return context.Entry(targetAddress).ToObject(new Address());
}
}
谢谢!