我在下面看到了模型。我的目标是使用现有语言和工具插入新测试。我一直收到错误,说我试图为语言和工具插入的主键已经存在。看来这种方法正试图创建一种新的语言和一种新的设施。我只需要引用他们的ID而不是创建新的ID。
控制器方法
dbContext.TestSubjects.Add(model.TestSubject);
dbContext.SaveChanges();
Test test = new Test
{
Language = model.Language,
Facility = model.Facility,
TestSubject = model.TestSubject,
EvaluationState = "Not Started"
};
dbContext.Tests.Add(test);
dbContext.SaveChanges();
型号:
public int Id { get; set; }
public string EvaluationState { get; set; }
public virtual Language Language { get; set; }
public virtual Organization Facility { get; set; }
public virtual TestSubject TestSubject { get; set; }
答案 0 :(得分:0)
此示例按惯例使用外键:有关详细信息,请参阅Entity Framework Code First Conventions。
dbContext.TestSubjects.Add(model.TestSubject);
dbContext.SaveChanges();
Test test = new Test
{
// set your foreign key values
LanguageId = 1,
FacilityId = 12,
TestSubjectId = 22,
EvaluationState = "Not Started"
};
dbContext.Tests.Add(test);
dbContext.SaveChanges();
您需要扩展模型以告诉Entity Framework您的外键是什么样的:
public int Id { get; set; }
public string EvaluationState { get; set; }
public int LanguageId { get; set; }
public virtual Language Language { get; set; }
public int FacilityId { get; set; }
public virtual Organization Facility { get; set; }
public int TestSubjectId { get; set; }
public virtual TestSubject TestSubject { get; set; }