1
すべての謎には1つ以上の質問があります。どのように1つのフォームを送信してその謎に謎と質問の両方を追加できますか?1つのアクションに新しい関連エンティティを追加する
このRiddlesControllerはアクションコードを作成している:
public ActionResult Create(RiddleViewModel model)
{
if (ModelState.IsValid)
{
try
{
_db.Riddles.Add(new Models.Riddle
{
Name = model.Name,
Description = model.Description ,
CreationDate = DateTime.Now,
User = _db.Users.Find(User.Identity.GetUserId()),
});
_db.Questions.Add(new Models.Question
{
Body = model.FirstQuestionBody,
Answer = model.FirstQuestionAnswer,
CreationDate = DateTime.Now,
// What should I write here? or is there any better way to accomplish this?
Riddle = ?????
});
_db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
return View();
}
これは、謎のモデルコードです:
public class Riddle
{
public int Id { get; set; }
public string Name { get; set; }
[MaxLength(200)]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public List<Review> Reviews { get; set; }
[Required]
public ApplicationUser User { get; set; }
public virtual List<Question> Questions { get; set; }
[Column(TypeName = "datetime2")]
public DateTime CreationDate { get; set; }
}
これは質問のモデルコードです:
public class Question
{
public int Id { get; set; }
public string Body { get; set; }
public string Answer { get; set; }
public Riddle Riddle { get; set; }
[Column(TypeName ="datetime2")]
public DateTime CreationDate { get; set; }
}
これはRiddleViewModelコードです:
public class RiddleViewModel
{
[Required]
public string Name { get; set; }
[MaxLength(200)]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
// Question properties
[DataType(DataType.MultilineText)]
public string FirstQuestionBody { get; set; }
public string FirstQuestionAnswer { get; set; }
}
あなたのモデルコードも表示できますか? image.justコードを貼り付けてはいけません。 – Sampath
ここに新しい、コメントにコードを追加する方法が見つかりませんでした。 1秒 – Gimballock
@Sampath大丈夫です。 – Gimballock