私は2つのエンティティを持っていますコンテキストへのParentThingと変更を保存しようとします。必要に応じて、ParentThingのTheSecondThingプロパティのCodeプロパティで検証エラーが表示されます。MVC必須のプロパティ
必要なプロパティを含むオプションのプロパティを保存するためのいくつかの選択肢はありますか?
私は2つのエンティティを持っていますコンテキストへのParentThingと変更を保存しようとします。必要に応じて、ParentThingのTheSecondThingプロパティのCodeプロパティで検証エラーが表示されます。MVC必須のプロパティ
必要なプロパティを含むオプションのプロパティを保存するためのいくつかの選択肢はありますか?
jamieが示唆しているように、エンティティとモデルの間の依存関係を取り除きます... 2つの別々のもの エンティティでデータアノテーションを使用しないで、モデル上でデータアノテーションを使用します。モデルのParentThingプロパティを削除し、必要に応じてモデル内にプリミティブなプロパティ(Message、ParentThingId、TheFirstThingId、TheFirstThingCode、TheFirstThingNameなど)を追加し、すべてのデータ注釈属性をモデルに追加します。エンティティを検証する必要がある場合(おそらく)、ビジネスロジック上でそれを行います。
レオ。
現在の提案に応じて、これは私が現在持っているものです。
エンティティは同じままです。
修飾ビューモデル:
public class ParentViewModel
{
public string Message { get; set; }
public string FirstThingCode { get; set; }
public string FirstThingName { get; set; }
public string SecondThingCode { get; set; }
public string SecondThingName { get; set; }
}
修飾ビュー:
@using (@Html.BeginForm())
{
<label>Code 1</label>
@Html.EditorFor(model => model.FirstThingCode)
<label>Name 1</label>
@Html.EditorFor(model => model.FirstThingName)
<label>Code 2</label>
@Html.EditorFor(model => model.SecondThingCode)
<label>Name 2</label>
@Html.EditorFor(model => model.SecondThingName)
<input type="submit" value="Save" />
}
DTO:
public class ParentThingDTO
{
public ParentThingDTO(ParentViewModel model)
{
FirstThingCode = model.FirstThingCode;
FirstThingName = model.FirstThingName;
SecondThingCode = model.SecondThingCode;
SecondThingName = model.SecondThingName;
}
public int Id { get; set; }
public string FirstThingCode { get; set; }
public string FirstThingName { get; set; }
public string SecondThingCode { get; set; }
public string SecondThingName { get; set; }
public ParentThing GenerateEntity()
{
var thing = new ParentThing();
thing.TheFirstThing = new ChildThing
{
Code = FirstThingCode,
Name = FirstThingName
};
if (!string.IsNullOrWhiteSpace(SecondThingCode))
{
thing.TheSecondThing = new ChildThing
{
Code = SecondThingCode,
Name = SecondThingName
};
}
return thing;
}
}
コントローラにポストバックアクション:
[HttpPost]
public ActionResult Create(ParentViewModel model)
{
try
{
var dto = new ParentThingDTO(model);
var parentThing = dto.GenerateEntity();
using (var context = new QuantumContext())
{
context.ParentThings.Add(parentThing);
context.SaveChanges();
model.Message = "Saved";
}
}
catch (Exception ex)
{
model.Message = ex.Message;
}
return View(model);
}
dto GenerateEntityメソッドのnullまたは空白のテストは、オプションプロパティ内のMVC必須プロパティの私の最初の問題を解決します。どのように見えるのですか?
新しいParentThingを生成するのではなく、行を編集するときに 'ParentThing'インスタンスを検索して(idで)検索します。次に、あなたの 'ParentThingDTO'から入ってくる新しい値に基づいてエンティティ値を編集します。作成時には、既存の行がないので、新しいエンティティを作成しても安全です。 – Jasen
代わりに、ビューモデル内のエンティティクラスへの依存関係を削除することもできます。データ転送オブジェクト(DTO)を使用する必要があります。このhttp://stackoverflow.com/questions/5995140/models-viewmodels-dtos-in-mvc-3-applicationは、使い始めるのに役立ちます。 – Jasen