I have the model visible below. My goal is to insert a new test with an existing Language and Facility. I keep getting the error saying the primary key I am trying to insert for Language and Facility already exists. It seems this method is trying to create a new Language and a new Facility. I just need to reference their ID's not create new.
Controller Method
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();
Model:
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; }
This example uses the foreign key by convention: see Entity Framework Code First Conventions for more details.
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();
You need to extend your model to tell Entity Framework what your foreign keys are like:
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; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.