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 : '{'UserId '}에 대해 동일한 키 값을 가진 다른 인스턴스가 이미 추적 중이므로'UserCourse '엔터티 유형의 인스턴스를 추적 할 수 없습니다. 기존 엔터티를 연결할 때 지정된 키 값이있는 엔터티 인스턴스가 하나만 연결되었는지 확인합니다. 충돌하는 키 값을 보려면 '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 = "[email protected]";
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이 DbInitializer.cs의 var에 선언 된 "a @ bc"가 아닌 경우에만 앱이 작동하는 것 같습니다.
오류의 원인은를 사용 [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에서 Key (primary)를 설정하는 방법 에 대한 설명서를 참조 할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다