我希望在反序列化后更新我的实体。 问题是每次我必须找到特定实体并逐个更新属性。 还有其他方法吗? 我使用了Attach,但它只适用于新项目。 这是我的代码:
public string PersistTask(string task)
{
var result = string.Empty;
try
{
var model = new TaskTrackingModelContainer();
var rawTask = JsonConvert.DeserializeObject<Task>(task);
if (rawTask.Id != 0) // Edit, Delete
{
var oldTask = model.Tasks.FirstOrDefault(a => a.Id == rawTask.Id);
if (rawTask.IsDeleted)
{
model.Tasks.Remove(oldTask);
result = "Delete Successfully";
}
else
{
oldTask.Title = rawTask.Title;
rawTask.TaskHistories.ToList().ForEach(delegate (TaskHistory newHistory)
{
var oldHistory = oldTask.TaskHistories.FirstOrDefault(oldh => oldh.Id == newHistory.Id);
oldHistory.ModifiedDate = newHistory.ModifiedDate;
oldHistory.Description = newHistory.Description;
});
result = "Update Successfully";
}
}
else // New
{
model.Tasks.Add(rawTask);
result = "Add Successfully";
}
model.SaveChanges();
}
catch (Exception ex)
{
result = ex.ToString();
}
return result;
}