如何将新对象添加到现有实体中,PUT数据并让EF将其添加到我的数据库中
本文关键字:添加 PUT 数据 数据库 我的 EF 新对象 对象 实体 | 更新日期: 2023-09-27 18:25:31
我使用的是EF5、SQL Server 2012和Web前端。在服务器上,我有以下两个类:
public class Question
{
public Question()
{
this.Answers = new List<Answer>();
}
public int QuestionId { get; set; }
public string Title { get; set; }
public string Answer { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}
public class Answer
{
public int AnswerId { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
}
我在前端应用程序中检索到一个问题,添加了一个空答案:
var emptyAnswer = { "answerswerId"; null, "text": "xx", "questionId": formData.questionId};
formData.answers.push(emptyAnswer);
然后我对服务器进行了PUT,并注意到当它到达服务器时,answerId被正确地设置为null。
public HttpResponseMessage PutQuestion(int id, Question question)
{
var a = question;
}
数据由我的ASP.NET WebApi控制器接收,但当我检查新创建的答案对象(现在是问题的一部分)时,它的AnswerId为0。
有人能告诉我为什么它从null变为0吗?问题是,当我现在更新实体时框架给了我一个错误,因为它期望新创建的答案没有设置它的AnswerId。
请注意。在对象到达实体框架之前,我正在进行检查。我提到我正在使用它,但在这一点上,我认为它还没有出现在画面中,因为我只是检查了poco类。下文提到该字段不可为null。然而,当我创建一个新对象时,有效负载是类似的,例如,当我新建一个"内容"对象时,我将字段设置为null,并且它保持为null。
这是我到目前为止的测试结果。我把前端从循环中去掉了,所以一切都更清楚了:
作品:
var a = new Answer{
Correct = false,
Response = false,
Text = "AA",
Image = "DDD",
QuestionId = question.QuestionId
};
question.Answers.Add(a);
_uow.Questions.Update(question);
_uow.Commit();
不起作用:ObjectStateManager中已存在具有相同键的对象。ObjectStateManager无法跟踪具有相同键的多个对象。
var a = new Answer{
AnswerId = 0,
Correct = false,
Response = false,
Text = "AAA",
Image = "DDD",
QuestionId = question.QuestionId
};
var b = new Answer
{
AnswerId = 0,
Correct = false,
Response = false,
Text = "BBB",
Image = "EEE",
QuestionId = question.QuestionId
};
工作不正常。它不会创建新的实体值。它只使用1000和1001
var a = new Answer{
AnswerId = 1000,
Correct = false,
Response = false,
Text = "AAA",
Image = "DDD",
QuestionId = question.QuestionId
};
var b = new Answer
{
AnswerId = 1001,
Correct = false,
Response = false,
Text = "BBB",
Image = "EEE",
QuestionId = question.QuestionId
};
不起作用:编译器错误。无法将null转换为int
var a = new Answer{
AnswerId = null,
Correct = false,
Response = false,
Text = "AAA",
Image = "DDD",
QuestionId = question.QuestionId
};
var b = new Answer
{
AnswerId = null,
Correct = false,
Response = false,
Text = "BBB",
Image = "EEE",
QuestionId = question.QuestionId
};
不起作用:ObjectStateManager无法跟踪具有相同键的多个对象。
var a = new Answer{
Correct = false,
Response = false,
Text = "AAA",
Image = "DDD",
QuestionId = question.QuestionId
};
var b = new Answer
{
Correct = false,
Response = false,
Text = "BBB",
Image = "EEE",
QuestionId = question.QuestionId
};
这是因为Answer上的AnswerId属性不能为空
public class Answer
{
public int AnswerId { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
}
此外,EF显然认为您将设置适当的id。如果将AnswerId配置为标识列(自动递增id),则EF不会抱怨。