我不确定您想要实现的目标是否可行。至少不是Delta<TEntity>.Patch(..)
假设您有 Product 实体并且在您的 PATCH 操作中的某处您有
[AcceptVerbs("PATCH")]
public void Patch(int productId, Delta<Product> product)
{
var productFromDb = // get product from db by productId
product.Patch(productFromDb);
// some other stuff
}
当product被创建时,它在内部调用Delta<TEntityType>构造函数,看起来像这样(无参构造函数也调用这个,传递typeof(TEntityType)
public Delta(Type entityType)
{
this.Initialize(entityType);
}
Initialize 方法如下所示
private void Initialize(Type entityType)
{
// some argument validation, emitted for the sake of brevity
this._entity = (Activator.CreateInstance(entityType) as TEntityType);
this._changedProperties = new HashSet<string>();
this._entityType = entityType;
this._propertiesThatExist = this.InitializePropertiesThatExist();
}
这里有趣的部分是this._propertiesThatExist,它是一个Dictionary<string, PropertyAccessor<TEntityType>>,它包含产品类型的属性。 PropertyAccessor<TEntityType> 是内部类型,可以更轻松地操作属性。
当您致电 product.Patch(productFromDb) 时,这就是幕后发生的事情
// some argument checks
PropertyAccessor<TEntityType>[] array = (
from s in this.GetChangedPropertyNames()
select this._propertiesThatExist[s]).ToArray<PropertyAccessor<TEntityType>>();
PropertyAccessor<TEntityType>[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
PropertyAccessor<TEntityType> propertyAccessor = array2[i];
propertyAccessor.Copy(this._entity, original);
}
正如您所看到的,它获取已更改的属性,对其进行迭代并将值从传递给 Patch 操作的实例设置为您从 db 获取的实例。因此,您传递的操作、要添加的属性名称和值不会反映任何内容。
propertyAccessor.Copy(this._entity, original) 方法体
public void Copy(TEntityType from, TEntityType to)
{
if (from == null)
{
throw Error.ArgumentNull("from");
}
if (to == null)
{
throw Error.ArgumentNull("to");
}
this.SetValue(to, this.GetValue(from));
}