尝试运行Web应用程序时出现System.InvalidOperationException

时间:2019-10-29 16:08:15

标签: c# entity-framework asp.net-core-mvc entity-framework-core

我是ASP.NET Core 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'}的键值已被跟踪。连接时   现有实体,请确保只有一个实体实例具有给定   键值已附加。考虑使用   'DbContextOptionsBuilder.EnableSensitiveDataLogging'以查看   冲突的键值。'

让我知道您是否需要更多详细信息或代码。

请帮助我,因为我无法继续使用我的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();
        }

    }
}

VOD.Database.Contexts.VODContext 中的代码可以在下面找到:

public class VODContext : IdentityDbContext<VODUser>
{
    public DbSet<Course> Courses { get; set; }
    public DbSet<Download> Downloads { get; set; }
    public DbSet<Instructor> Instructors { get; set; }
    public DbSet<Module> Modules { get; set; }
    public DbSet<UserCourse> UserCourses { get; set; }
    public DbSet<Video> Videos { get; set; }
    public VODContext(DbContextOptions<VODContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        // Composite key
        builder.Entity<UserCourse>().HasKey(uc => new { uc.UserId, uc.CourseId });

        // Restrict cascading deletes
        foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationship.DeleteBehavior = DeleteBehavior.Restrict;
        }
    }
}

下面是 VOD.Common.Entities.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; }
}

似乎只有当我的表dbo.AspNetUsers为空或者如果提到的表中的UserName不是“ a @ bc”(在var中在DbInitializer.cs中声明)时,该应用程序才能运行。 / p>

1 个答案:

答案 0 :(得分:0)

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

您应该删除[Key]中的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; }
}

您可以参考how to set the Key(primary) in EF Core上的文档。