实体框架方法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 但相反的方法?
还有另一个称为 ToObject 的 DbPropertyValues 方法,但它不适用于 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());
}
}
谢谢!