MVC EF建立关系

时间:2016-03-03 23:20:01

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

我正在尝试映射以下内容:

用户与管理员1到0..1的关系。一个用户可以是一种管理员状态或没有管理员状态

用户可以打开多张票证,但票证只能分配给一个用户。用户1票证到多人

管理员(具有管理员身份的用户)已分配给他修复的故障单。票证应该有一个adminID来标识分配给它的管理员。

有人可以验证我的映射是否正确

我的故障单表格如何CLICK HERE

modelBuilder.Entity<Ticket>()
    .HasMany(c => c.Administrators).WithMany(i => i.Tickets)
    .Map(t => t.MapLeftKey("TicketID")
        .MapRightKey("AdministratorID")
        .ToTable("AdministratorsTickets"));


modelBuilder.Entity<Administrator>()
           .HasKey(e => e.UserID);

modelBuilder.Entity<User>()
    .HasOptional(s => s.Administrator) // Mark StudentAddress is optional for Student
    .WithRequired(ad => ad.User); // Create inverse relationship

Configuration.cs

public Configuration()
{
    AutomaticMigrationsEnabled = false;
}

protected override void Seed(RecreationalServicesTicketingSystem.DAL.IssueContext context)
{
    var departments = new List<Department>
    {
        new Department { DepartmentID = 1, Name = "IT"},
        new Department { DepartmentID = 2, Name = "Admin" },
        new Department { DepartmentID = 3, Name = "Human Resources"},
        new Department { DepartmentID = 4, Name = "Mechanics" },
        new Department { DepartmentID = 5, Name = "Directors" },
        new Department { DepartmentID = 6, Name = "Operations"}

    };
    departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s));
    context.SaveChanges();


    var depots = new List<Depot>
    {
        new Depot { DepotID = 1, Name = "Porana"},
        new Depot { DepotID = 2, Name = "Far North"},


    };
    depots.ForEach(s => context.Depots.AddOrUpdate(p => p.Name, s));
    context.SaveChanges();

    var users = new List<User>
{
    new User { FirstMidName = "Jason",   LastName = "Wan",
        EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1, DepotID = 1},
    new User { FirstMidName = "Andy", LastName = "Domagas",
        EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1,DepotID = 1},
    new User { FirstMidName = "Denis",   LastName = "Djohar",
        EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1 ,DepotID = 1},
    new User { FirstMidName = "Christine",   LastName = "West",
        EnrollmentDate = DateTime.Parse("2016-02-18"), DepartmentID = 1, DepotID = 1},

};


    users.ForEach(s => context.Users.AddOrUpdate(p => p.FirstMidName, s));
    context.SaveChanges();

    users.ForEach(s => context.Users.AddOrUpdate(p => p.LastName, s));
    context.SaveChanges();


    var administrator = new List<Administrator>
    {
        new Administrator {AdminID = 1, AdminRole = "Administrator LVL1", User = users.Single ( s => s.UserID == 1),
        Tickets = new List<Ticket>() },
        new Administrator {AdminID = 2, AdminRole = "Administrator LVL2", User = users.Single ( s => s.UserID == 2),
        Tickets = new List<Ticket>() },
        new Administrator {AdminID = 3, AdminRole = "Administrator LVL3", User = users.Single ( s => s.UserID == 3),
        Tickets = new List<Ticket>() }

    };
    administrator.ForEach(s => context.Administrators.AddOrUpdate(p => p.AdminID, s));
    context.SaveChanges();

    var categories = new List<Category>
    {
        new Category {CategoryID = 0001, Title = "Desktop"},
        new Category {CategoryID = 0002, Title = "Mobile"},
        new Category {CategoryID = 0003, Title = "Menzits"},
        new Category {CategoryID = 0004, Title = "XMPRO"},
        new Category {CategoryID = 0005, Title = "Con-X"},
        new Category {CategoryID = 0006, Title = "Promapp"},
        new Category {CategoryID = 0007, Title = "QGIS"},
    };
    categories.ForEach(s => context.Categories.AddOrUpdate(p => p.Title, s));
    context.SaveChanges();

    var tickets = new List<Ticket>
    {
        new Ticket {
            UserID = users.Single(s => s.LastName == "Wan").UserID,
            CategoryID = categories.Single(c => c.Title == "Con-X" ).CategoryID,
            Issue = ("Test Error NEW TEST"),
            AdminID = 1,
            Priority = Priority.High
        },
        new Ticket {
            UserID = users.Single(s => s.LastName == "Wan").UserID,
            CategoryID = categories.Single(c => c.Title == "Desktop" ).CategoryID,
            Issue = ("Test Error 2"),
            AdminID = 2,
            Priority = Priority.Med
        },
    };


    foreach (Ticket e in tickets)
    {
        var ticketInDataBase = context.Tickets.Where(
            s =>
                s.User.UserID == e.UserID &&
                s.Category.CategoryID == e.CategoryID).SingleOrDefault();
        if (ticketInDataBase == null)
        {
            context.Tickets.Add(e);
        }
    }
    context.SaveChanges();
}

Ticket.cs

public enum Priority
{
    Low, Med, High
}

public class Ticket
{
    public string Issue { get; set; }
    [DisplayFormat(NullDisplayText = "No Priority")]
    public Priority? Priority { get; set; }
    public int CategoryID { get; set; }
    [ForeignKey("CategoryID")]
    public virtual Category Category { get; set; }
    public int TicketID { get; set; }
    public int AdminID { get; set; }
    public virtual ICollection<Administrator> Administrators { get; set; }
    public int UserID { get; set; }
    //[ForeignKey("TicketID")]
    public virtual User User { get; set; }
}

User.cs

 public class User
{

    public int UserID { get; set; }
    [StringLength(50, MinimumLength = 1)]
    public string LastName { get; set; }
    [StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]

    [Column("FirstName")]
    public string FirstMidName { get; set; }

    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime EnrollmentDate { get; set; }

    public string FullName
    {
        get { return LastName + ", " + FirstMidName; }
    }
    public int AdministratorID { get; set; }
    [ForeignKey("AdministratorID")]
    public virtual Administrator Administrator { get; set; }

    public int DepartmentID { get; set; }
    [ForeignKey("DepartmentID")]
    public virtual Department Department { get; set; }


    public int DepotID { get; set; }
    [ForeignKey("DepotID")]
    public virtual Depot Depot { get; set; }

    public int TicketID { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }

}

Administrator.cs

public class Administrator
{
    [Key, ForeignKey("User")]
    public int UserID { get; set; }
    public int AdminID { get; set; }
    public int TicketID { get; set; }        
    [StringLength(50)]
    public string AdminRole { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }
    public virtual User User { get; set; }
}

IssueContext.cs

   public class IssueContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Ticket> Tickets { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Department> Departments { get; set; }
        public DbSet<Administrator> Administrators { get; set; }
        public DbSet<Depot> Depots { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

            modelBuilder.Entity<Ticket>()
                .HasMany(c => c.Administrators).WithMany(i => i.Tickets)
                .Map(t => t.MapLeftKey("TicketID")
                    .MapRightKey("AdministratorID")
                    .ToTable("AdministratorsTickets"));


            modelBuilder.Entity<Administrator>()
                       .HasKey(e => e.UserID);

            modelBuilder.Entity<User>()
                .HasOptional(s => s.Administrator) // Mark StudentAddress is optional for Student
                .WithRequired(ad => ad.User); // Create inverse relationship


        }
    }

1 个答案:

答案 0 :(得分:0)

映射不是100%正确,这些部分对我来说是错误的:

modelBuilder.Entity<Administrator>()
           .HasKey(e => e.UserID);

[Key, ForeignKey("User")]
public int UserID { get; set; }

从这些行看起来您正在使用Administrator.UserID同时使用主键和外键。

相反,您应该将您的Administrator.AdministratorId设为主键:

modelBuilder.Entity<Administrator>()
           .HasKey(e => e.AdministratorID);

public class Administrator
{
    [Key]
    public int AdminID { get; set; }
    [ForeignKey("User")]
    public int UserID { get; set; }
    public int TicketID { get; set; }        
    [StringLength(50)]
    public string AdminRole { get; set; }
    public virtual ICollection<Ticket> Tickets { get; set; }
    public virtual User User { get; set; }
}

此外,我还不能100%确定您在管理员和故障单之间有正确的映射:您从管理员/用户到故障单之间有1对多的关系,但您仍然在管理员和用户中拥有外键TicketID类,这也是不正确的。