未更新/添加.NET核心的子实体



我正在创建一个web应用程序,该应用程序使用.NET核心和实体框架来保存具有多个答案的问题。目前正在为我的Question实体开发Add new和Update方法,我的剃刀页面上有一个表单,可以很好地用于Question部分,但Answer实体没有添加/更新。

实体的结构是一对多的关系,每个问题有4个答案链接到它。实体的代码如下:

public class Question
{
public int ID { get; set; }
public string QuestionBody { get; set; }
public List<Answer> Answers { get; set; }
public QuestionTypeID QuestionTypeID { get; set; }
public QuestionType QuestionType { get; set; }
public Question()
{
Answers = new List<Answer>();
}
}
public class Answer
{
public int ID { get; set; }
public string AnswerBody { get; set; }
public Boolean IsTrue { get; set; }
public Question Question { get; set; }
public int QuestionID { get; set; }
}

我是.NET的新手,作为论文的一部分,我不得不自学,不确定为什么问题存储/更新在数据库中很好,但答案似乎没有附着在实体上,也没有更新数据库。

这是表格:

<form method="post">
<input type="hidden" asp-for="Question.ID" />
<div class="form-group">
<label asp-for="Question.QuestionBody"></label>
<input asp-for="Question.QuestionBody" class="form-control" />
<span class="text-danger" asp-validation-for="Question.QuestionBody"></span>
</div>
<div class="col-form-label">
Answers
@{
var count = 0;
while (@Model.newQuestion && count < EditModel.MaxAnswerLength)
{
<input asp-for="@Model.Question.Answers" class="form-control" />
<span class="text-danger" asp-validation-for="Answer"></span>
<br />
count++;
}
}
@foreach (var answer in Model.Question.Answers)
{
<div class="form-group">
<input asp-for="@answer.AnswerBody" class="form-control" />
<span class="text-danger" asp-validation-for="Answer.AnswerBody"></span>
</div>
}
</div>
<div class="form-group">
<label asp-for="Question.QuestionTypeID"></label>
<select asp-for="Question.QuestionTypeID" class="form-control" asp-items="Model.QuestionTypes">
<option></option>
</select>
<span class="text-danger" asp-validation-for="Question.QuestionTypeID"></span>
</div>
<button type="submit" class="btn btn-primary">Save</button>
<a asp-page="List" class="btn btn-danger">Cancel</a>
</form>

以及OnPost方法:

public IActionResult OnPost()
{
if (!ModelState.IsValid)
{
QuestionTypes = htmlHelper.GetEnumSelectList<QuestionTypeID>();
return Page();
}

if (Question.ID > 0)
{
questionData.UpdateQuestion(Question);
}
else
{
questionData.AddQuestion(Question);
}
questionData.Commit();
TempData["Message"] = "Question Saved!";
return RedirectToPage("./Detail", new { QuestionID = Question.ID });
}

我对EF不太熟悉,所以我尝试创建一个AddQuestion的方法,它只包含以下内容:

public Question AddQuestion(Question question)
{
db.Questions.Add(question);
return question;
}

Update方法还没有实现,因为我尝试的任何方法都不起作用,所以我认为最好从添加开始,然后在它起作用时重新调整用途。

我相信这个问题可能在表格中的某个地方,但我也不确定我是否遗漏了这个Add方法中应该包含的关于特定添加答案的内容,所以如果有任何帮助,我们将不胜感激!!

因为您使用的是列表,所以需要索引,而使用foreach循环,您无法在视图中实现这一点。相反,请尝试使用for:

@for (int i = 0; i < Model.Question.Answers.Count; i++)
{
<div class="form-group">
<input asp-for="Question.Answers[i].AnswerBody" class="form-control" />
<span class="text-danger" asp-validation-for="Question.Answers[i].AnswerBody"></span>
</div>
}

最新更新