查询相关数据Asp.Net Core MVC时如何解决“ 500错误”

时间:2019-10-08 13:23:21

标签: asp.net-mvc

    public class ApplicationUser : IdentityUser<Guid>
    {
        public EmergencyContact EmergencyContact { get; set; }

        public Instructor Instructor { get; set; }

        public List<CourseStudent> StudentCourses { get; set; }
    }

这是我的自定义用户类别 然后这是我的加入课程,其中包含用户和课程

public class CourseStudent
    {
        public Guid StudentId { get; set; }
        public ApplicationUser Student { get; set; }

        public Guid CourseId { get; set; }
        public Course Course { get; set; }
    }

我无法向User.StudentCourse插入数据,它给了我500状态代码。

然后这就是我的情况

modelBuilder.Entity<CourseStudent>()
                .HasKey(e => new {
                e.CourseId,
                e.StudentId
            });

            modelBuilder.Entity<CourseStudent>()
                .HasOne(e => e.Student)
                .WithMany(e => e.StudentCourses)
                .HasForeignKey(e => e.StudentId)
                .OnDelete(DeleteBehavior.Restrict);

            modelBuilder.Entity<CourseStudent>()
                .HasOne(e => e.Course)
                .WithMany(e => e.CourseStudents)
                .HasForeignKey(e => e.CourseId)
                .OnDelete(DeleteBehavior.Restrict);

我无法访问用户课程。如何解决这个问题

1 个答案:

答案 0 :(得分:-1)

这就是我处理多对多关系的方式:
用户:

public class User
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity), Key] public Guid Id { get; set; }
        ...

        public ICollection<UserGroup> UserGroups { get; set; }
    }

组(以您的情况为准):

public class Group
{
    [Key]
    public Guid Id { get; set; }
    ...

    public ICollection<UserGroup> UserGroups { get; set; }
}

UserGroup(联接表):

public class UserGroup
    {
        [Required]
        public Guid UserId { get; set; }
        public User User { get; set; }

        [Required]
        public Guid GroupId { get; set; }
        public Group Group { get; set; }

    }

在上下文文件中:

protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserGroup>().HasKey(ug => new { ug.UserId, ug.GroupId });
        }
        public DbSet<User> Users { get; set; }
        public DbSet<Group> Groups { get; set; }
        public DbSet<UserGroup> UserGroups { get; set; }