私はwebapiで作業しています。私は修正を行うための1つの更新メソッドを持っています。プロパティの数がありますが、私はいくつかのフィールドを更新したいだけです。未修正のフィールドは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;
}
}
私が話したように、すべての論理作業罰金。しかし、レスポンスを表示すると、更新されていないフィールドはnullとして表示されます。たとえば、RegistrationId、Codeなどですが、データベースには何も更新されていません。
エンティティをビューに渡すのではなく、ビューモデルを使用し、そのビューモデルをドメイン(リポジトリ)に戻して現在のエンティティを取得し、必要なフィールドを更新することをおすすめします。あなたの例では、リポジトリに渡したモデルのこれらの#nullフィールドの値は何でしたか?リポジトリに送信されたモデルが不完全で、コンテキストにアタッチし、「Modified」に設定し、一部のプロパティを無視したが、DBから期待される値が添付されたエンティティに移入するケースのように聞こえるでしょうか? (エントリー) –
@StevePyありがとう。私はすでにviewmodelのみを使用しました。渡されなかったプロパティ(変更されていないとマークされます)はnullとして返されますが、db値は更新されません。私はまた、あなたが既存のオブジェクトを取り、更新中にプロパティを更新することによって伝えたのと同じようにしました。私はその場合、同じプライマリキーを持つ別のコンテキストを持っているようないくつかのエラーが発生しました – Akhil
[計算またはID]としていくつかのプロパティをマップする必要があるように見えます(https://msdn.microsoft.com/en-us/library/system.componentmodel .dataannotations.schema.databasegeneratedoption(v = vs.110).aspx)。 –