Я получаю System.InvalidOperationException при попытке запустить веб-приложение - PullRequest
1 голос
/ 29 октября 2019

Я новичок в 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', чтобы увидеть конфликтующие ключевые значения. '

Дайте мне знать, если вам нужны дополнительные сведения или код.

Пожалуйста, помогите мне в этом, как я могу'Продолжить работу с моим веб-приложением.

Позже отредактируйте : ниже вы можете найти весь метод, расположенный в 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 или если имя пользователя из упомянутой таблицы не является "a @ bc" - которое объявлено впеременная, в DbInitializer.cs.

1 Ответ

0 голосов
/ 30 октября 2019

Причиной ошибки является то, что вы используете [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; }
}

Вы можете обратиться к документации по , как установить Ключ (основной) в EF Core .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...