gpt4 book ai didi

c# - 为什么 EF7/Core 插入重复记录?

转载 作者:太空宇宙 更新时间:2023-11-03 23:08:23 24 4
gpt4 key购买 nike

在我的领域模型中我有

class School
{
public ICollection<Student> Students { get; set; }
}

class Student
{
public ICollection<Course> Courses { get; set; }
}

class Teacher
{
public ICollection<Course> Courses { get; set; }
}

class Course
{
public Student Student { get; set; }

public Teacher Teacher { get; set; }
}

假设我的数据库中已经有一个学生和一个老师

Student ID = {C26A6D90-6D36-4CE9-9FF0-5C5BAB6994CC}

Teacher ID = {26ECCCC6-4A24-4FB2-A406-5021B693EE5E}

然后我想创建一个新类(class)

Course c = new Course(student, teacher);
repo.Add(c);
repo.Save();
  1. 我收到一条错误消息,提示我无法使用相同 ID 重新创建学校
  2. 我收到一条错误消息,告诉我无法重新创建具有相同 ID 的学生

基本上,我从数据库中获取记录(Student & Teacher),然后尝试使用它们创建一个新的关系实体(类(class))

{System.Data.SqlClient.SqlException: Violation of PRIMARY KEY constraint 'PK_Schools'. Cannot insert duplicate key in object 'dbo.Schools'. The duplicate key value is (78434ef7-20db-42c8-448e-08d401d04461). The statement has been terminated.

这似乎是一个 EF7 问题...它是否还不够成熟 - 因为它不像它!

最佳答案

非常感谢CodeNotFound谁值得奖杯......

Make sure you're using the same DbContext

所以我改了AddTransient<,>AddSingleton<,>在我的服务配置中,嘿-presto!行得通!

也感谢D Stanley对于这个有用的片段:

To be fair to those that aren't using DI, another option is to Attach the student and teacher objects to the context before saving the course. Attach tells EF that the object already exists in the database and shouldn't be added again.

如果你找到了这个,请想想那些在你之前走过的人!

关于c# - 为什么 EF7/Core 插入重复记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40351103/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com