我正在從事webapi工作。我有一個更新方法來執行修改。有很多屬性,但我只想更新幾個字段。Unmodified fields are not getting WebAPI
所以我只是跳過不需要的字段使用entry.Property(propertyName).IsModified = false;在數據層。我所有的邏輯工作正常,但更新後,當我得到了新的更新項,它沒有未更新
我的控制器代碼字段:
[Route("{id:int}")]
public async Task<IHttpActionResult> Put(int id, MyModel model)
{
model.Id = id;
bool result = await _modelLogic.UpdateData(item);
if (!result)
{
return BadRequest("Could not Save to the database");
}
return await GetModel(item.Id);
}
[Route("{id:int}", Name = "GetModelById")]
public async Task<IHttpActionResult> GetModel(int id)
{
MyModel model = await _modelLogic.GetModelAsync(id);
if (Model == null)
{
return NotFound();
}
return Ok(model);
}
我的業務邏輯:
public async Task<bool> UpdateData(MyModel model)
{
model.RecordStatus = DataStatus.Active;
string[] excludedProperties = new[] {"RegistrationId", "StartDate", "ProtocolType", "Code" };
_repo.Update(model, excludedProperties);
bool status = await _repo.SaveAsync();
return status;
}
這裏RegistrationId是一個外鍵。
我的數據代碼:
public void Update(MyModel model, string[] excludedProperties)
{
excludedPropertiesInUpdate = excludedPropertiesInUpdate.Union(excludedProperties).ToArray();
base.Update(model);
}
我的通用存儲庫/基礎庫
internal string[] excludedPropertiesInUpdate = new[] { "CreatedDate", "CreatedBy" };
public void Update(T entity)
{
entity.UpdatedDate = DateTime.UtcNow;
var entry = _context.Entry(entity);
entry.State = EntityState.Modified;
//Restrict Modification for Specified Properties
foreach(string propertyName in excludedPropertiesInUpdate)
{
entry.Property(propertyName).IsModified = false;
}
}
就像我說,所有的邏輯工作的罰款。但是當它顯示響應時,未更新的字段顯示爲空。例如:RegistrationId,Code等。但是在數據庫中它沒有更新任何東西
我不推薦將實體傳遞給視圖,而是使用視圖模型,然後在將視圖模型傳遞迴域(存儲庫)時檢索當前實體並更新所需的字段。在您的示例中,您傳遞給存儲庫的模型中的這些#null字段的值是什麼?它幾乎聽起來可能是發送到存儲庫的模型不完整,您將其附加到上下文,將其設置爲「Modified」,忽略了一些屬性,但是來自DB的期望值用於填充附加的實體? (entry) –
@StevePy謝謝。我已經使用viewmodel only.The未通過(未標記爲未修改)的屬性返回爲空但在db值沒有更新。我也採用了與更新時更新屬性相同的方式。我遇到了一些錯誤,如你有另一個具有相同主鍵的上下文 – Akhil
看起來你應該將一些屬性映射爲[computed或identity](https://msdn.microsoft.com/en-us/library/system.componentmodel .dataannotations.schema.databasegeneratedoption(v = vs.110)的.aspx)。 –