我不确定您要实现的目标是否可行。至少不与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>>
包含 Product 类型的属性。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));
}