C# 尝试运行web应用时,我收到System.InvalidOperationException

C# 尝试运行web应用时,我收到System.InvalidOperationException,c#,entity-framework,asp.net-core-mvc,entity-framework-core,C#,Entity Framework,Asp.net Core Mvc,Entity Framework Core,我是ASP.NET核心MVC和EF的新手,我正在尝试运行以下代码: if (!context.UserCourses.Any()) { if (!courseId1.Equals(int.MinValue)) context.UserCourses.Add(new UserCourse { UserId = userId, CourseId = courseId1 }); if (!courseId2.Equals(int.MinValue)) context.

我是ASP.NET核心MVC和EF的新手,我正在尝试运行以下代码:

if (!context.UserCourses.Any())
{
   if (!courseId1.Equals(int.MinValue))
     context.UserCourses.Add(new UserCourse { UserId = userId, CourseId = courseId1 });

   if (!courseId2.Equals(int.MinValue))
     context.UserCourses.Add(new UserCourse { UserId = userId, CourseId = courseId2 });

   if (!courseId3.Equals(int.MinValue))
     context.UserCourses.Add(new UserCourse { UserId = userId, CourseId = courseId3 });

   context.SaveChanges();
}
但我有以下例外:

System.InvalidOperationException:'无法跟踪实体类型为'UserCourse'的实例,因为另一个实例具有相同的 正在跟踪{'UserId'}的键值。连接时 现有实体,请确保只有一个实体实例具有给定的 随附关键值。考虑使用 “DbContextOptions Builder.EnableSensivedAtalogging”以查看 相互冲突的键值。”

如果您需要更多详细信息或代码,请告诉我

请在这方面帮助我,因为我无法继续使用我的web应用程序

稍后编辑:您可以在下面找到整个方法,位于VOD.Database.Migrations.DbInitializer中:

public static void Initialize(VODContext context)
{
    var description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
    var email = "a@b.c";
    var adminRoleId = string.Empty;
    var userId = string.Empty;

    if (context.Users.Any(r => r.Email.Equals(email)))
        userId = context.Users.First(r => r.Email.Equals(email)).Id;

    if (!userId.Equals(string.Empty))
    {
        if (!context.Instructors.Any())
        {
            var instructors = new List<Instructor>
            {
                new Instructor
                {
                    Name = "John Doe",
                    Description = description.Substring(20, 50),
                    Thumbnail = "/images/Ice-Age-Scrat-icon.png"
                },

                new Instructor
                {
                    Name = "Jane Doe",
                    Description = description.Substring(30, 40),
                    Thumbnail = "/images/Ice-Age-Scrat-icon.png"
                }
            };
            context.Instructors.AddRange(instructors);
            context.SaveChanges();
        }

        if (!context.Courses.Any())
        {
            var instructorId1 = context.Instructors.First().Id;
            var instructorId2 = int.MinValue;
            var instructor = context.Instructors.Skip(1).FirstOrDefault();

            if (instructor != null) instructorId2 = instructor.Id;
            else instructorId2 = instructorId1;

            var courses = new List<Course>
            {
                new Course
                {
                    InstructorId = instructorId1,
                    Title = "Course 1",
                    Description = description,
                    ImageUrl = "/images/course1.jpg",
                    MarqueeImageUrl = "/images/laptop.jpg"
                },

                new Course
                {
                    InstructorId = instructorId2,
                    Title = "Course 2",
                    Description = description,
                    ImageUrl = "/images/course2.jpg",
                    MarqueeImageUrl = "/images/laptop.jpg"
                },

                new Course {
                    InstructorId = instructorId1,
                    Title = "Course 3",
                    Description = description,
                    ImageUrl = "/images/course3.jpg",
                    MarqueeImageUrl = "/images/laptop.jpg"
                }
            };
            context.Courses.AddRange(courses);
            context.SaveChanges();
        }

        var courseId1 = int.MinValue;
        var courseId2 = int.MinValue;
        var courseId3 = int.MinValue;

        if (context.Courses.Any())
        {
            courseId1 = context.Courses.First().Id;

            var course = context.Courses.Skip(1).FirstOrDefault();
            if (course != null) courseId2 = course.Id;

            course = context.Courses.Skip(2).FirstOrDefault();
            if (course != null) courseId3 = course.Id;
        }

        if (!context.UserCourses.Any())
        {
            if (!courseId1.Equals(int.MinValue))
                context.UserCourses.Add(new UserCourse { UserId = userId, CourseId = courseId1 });

            if (!courseId2.Equals(int.MinValue))
                context.UserCourses.Add(new UserCourse { UserId = userId, CourseId = courseId2 });

            if (!courseId3.Equals(int.MinValue))
                context.UserCourses.Add(new UserCourse { UserId = userId, CourseId = courseId3 });

            context.SaveChanges();
        }

        if (!context.Modules.Any())
        {
            var modules = new List<Module>
            {
                new Module { Course = context.Find<Course>(courseId1), Title = "Modeule 1" },
                new Module { Course = context.Find<Course>(courseId1), Title = "Modeule 2" },
                new Module { Course = context.Find<Course>(courseId2), Title = "Modeule 3" }
            };
            context.Modules.AddRange(modules);
            context.SaveChanges();
        }

        var moduleId1 = int.MinValue;
        var moduleId2 = int.MinValue;
        var moduleId3 = int.MinValue;
        if (context.Modules.Any())
        {
            moduleId1 = context.Modules.First().Id;

            var module = context.Modules.Skip(1).FirstOrDefault();
            if (module != null) moduleId2 = module.Id;
            else moduleId2 = moduleId1;

            module = context.Modules.Skip(2).FirstOrDefault();
            if (module != null) moduleId3 = module.Id;
            else moduleId3 = moduleId1;
        }

        if (!context.Videos.Any())
        {
            var videos = new List<Video>
        {
            new Video { ModuleId = moduleId1, CourseId = courseId1,
            Title = "Video 1 Title",
            Description = description.Substring(1, 35),
            Duration = 50, Thumbnail = "/images/video1.jpg",
            Url = "https://www.youtube.com/watch?v=BJFyzpBcaCY"
        },
            new Video { ModuleId = moduleId1, CourseId = courseId1,
            Title = "Video 2 Title",
            Description = description.Substring(5, 35),
            Duration = 45, Thumbnail = "/images/video2.jpg",
            Url = "https://www.youtube.com/watch?v=BJFyzpBcaCY"
        },
            new Video { ModuleId = moduleId1, CourseId = courseId1,
            Title = "Video 3 Title",
            Description = description.Substring(10, 35),
            Duration = 41, Thumbnail = "/images/video3.jpg",
            Url = "https://www.youtube.com/watch?v=BJFyzpBcaCY"
        },
            new Video { ModuleId = moduleId3, CourseId = courseId2,
            Title = "Video 4 Title",
            Description = description.Substring(15, 35),
            Duration = 41, Thumbnail = "/images/video4.jpg",
            Url = "https://www.youtube.com/watch?v=BJFyzpBcaCY"
        },
            new Video { ModuleId = moduleId2, CourseId = courseId1,
            Title = "Video 5 Title",
            Description = description.Substring(20, 35),
            Duration = 42, Thumbnail = "/images/video5.jpg",
            Url = "https://www.youtube.com/watch?v=BJFyzpBcaCY"
        }
        };
            context.Videos.AddRange(videos);
            context.SaveChanges();
        }

        if (!context.Downloads.Any())
        {
            var downloads = new List<Download>
            {
                new Download{ModuleId = moduleId1, CourseId = courseId1,
                    Title = "ADO.NET 1 (PDF)", Url = "https://some-url" },

                new Download{ModuleId = moduleId1, CourseId = courseId1,
                    Title = "ADO.NET 2 (PDF)", Url = "https://some-url" },

                new Download{ModuleId = moduleId3, CourseId = courseId2,
                    Title = "ADO.NET 1 (PDF)", Url = "https://some-url" }
            };

            context.Downloads.AddRange(downloads);
            context.SaveChanges();
        }

    }
}
public class UserCourse
{
    [Key]
    public string UserId { get; set; }
    public VODUser User { get; set; }
    public int CourseId { get; set; }
    public Course Course { get; set; }
}

似乎只有在表dbo.AspNetUsers为空或所述表中的用户名不是a@b.c“-在变量DbInitializer.cs中声明。

错误的原因是您使用
[Key]
在模型中设置主键,然后使用Fluent API设置复合密钥

您应该删除
UserCourse

public class UserCourse
{
   //[Key]
   public string UserId { get; set; }
   public VODUser User { get; set; }
   public int CourseId { get; set; }
   public Course Course { get; set; }
}

您可以参考上的文档。

错误的原因是您使用
[Key]
在模型中设置主键,然后使用Fluent API设置复合键

您应该删除
UserCourse

public class UserCourse
{
   //[Key]
   public string UserId { get; set; }
   public VODUser User { get; set; }
   public int CourseId { get; set; }
   public Course Course { get; set; }
}

您可以参考上的文档。

似乎
UserId
被定义为实体的
键。实体框架告诉您不能插入共享同一密钥的两个实体。大多数情况下,您会让Entity Framework处理密钥生成,而不是自己设置。此方法中还有其他代码吗?它抱怨您试图添加一个新的
UserCourse
,使用相同的
UserId
密钥。可能是您的3个if语句的计算结果都为true。请共享您的
UserCourse
模型和其他代码,以便我们提供进一步帮助。我刚刚在后面的编辑中添加了其他代码。似乎
UserId
被定义为您实体的
键。实体框架告诉您不能插入共享同一密钥的两个实体。大多数情况下,您会让Entity Framework处理密钥生成,而不是自己设置。此方法中还有其他代码吗?它抱怨您试图添加一个新的
UserCourse
,使用相同的
UserId
密钥。可能是您的3个if语句的计算结果都为true。请共享您的
UserCourse
模型和其他代码,以便我们提供进一步帮助。我刚刚在稍后的编辑中添加了其他代码。我已尝试删除
[Key]
来自
UserCourse
但我遇到以下异常:Microsoft.EntityFrameworkCore.DbUpdateException:“更新条目时出错。有关详细信息,请参见内部异常。“。SqlException:违反唯一密钥约束“AK_UserId”。无法在对象“dbo.UserCourses”中插入重复的密钥。重复的键值为(203fb77f-3a90-46df-817e-bcfaa5dc0eda)。声明已终止。在
context.SaveChanges()行上
@onetwo,从
UserCourses
中删除
[Key]
后,您是否重新迁移并更新了数据库?谢谢,@Xueli Chen。现在可以了。另外,谢谢你,因为这是解决方案,但我没有重新迁移和更新数据库。我已尝试从
UserCourse
中删除
[Key]
,但出现以下异常:Microsoft.EntityFrameworkCore.DbUpdateException:“更新条目时出错。”。有关详细信息,请参见内部异常。“。SqlException:违反唯一密钥约束“AK_UserId”。无法在对象“dbo.UserCourses”中插入重复的密钥。重复的键值为(203fb77f-3a90-46df-817e-bcfaa5dc0eda)。声明已终止。在
context.SaveChanges()行上
@onetwo,从
UserCourses
中删除
[Key]
后,您是否重新迁移并更新了数据库?谢谢,@Xueli Chen。现在可以了。另外,谢谢你,因为这是解决方案,但我没有重新迁移和更新数据库。