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