实体框架 - 如何在新对象内插入现有对象

时间:2018-04-10 03:56:32

标签: c# asp.net entity-framework

我在下面看到了模型。我的目标是使用现有语言和工具插入新测试。我一直收到错误,说我试图为语言和工具插入的主键已经存在。看来这种方法正试图创建一种新的语言和一种新的设施。我只需要引用他们的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; }

1 个答案:

答案 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; }