ASP.NET MVC实体框架代码优先:没有错误,但表格没有正确填充

时间:2016-03-04 12:04:54

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

我目前正在使用MVC4实体框架制作票务系统。我已经在我的SQL服务器中填充了我的表格,但只有少数几列不正确。首先,我想为代码量道歉,但它们都是引用所需的!

我只希望别人检查我是否正确映射我的模型,因为在图片(1)中缺少一些值。

请务必查看下面提供的两张图片,以便更清楚地了解我想要完成的工作。

图像(1)Here显示我想要的表格,并显示每个类的所有主键和外键。

此图片(2)Here显示我的实体图 所以我理想的情况是: 用户可以创建多个票证,他们只能将它们分配给一个管理员(这解决了故障单上的问题)。

每个故障单都将由TicketID标识,因此在Admin表中它应该具有AdminID,UserID(提交故障单的人),TicketID和AdminRole。

每个AdminID都可以分配给一个用户,但不是所有用户都必须分配给一个AdminID

DepotID,DepartmentID和Category非常简单。 必须将DepotID和DepartmentID分配给用户,并且每个用户只能有1个DepotID和DepartmentID

必须为每个故障单分配CategoryID,因此每个故障单只能有一个CategoryID

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 AdminID { get; set; }
    [ForeignKey("AdminID")]
    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; }

}

Ticket.cs

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; }

}

Depot.cs

public class Depot
{
    public int DepotID { get; set; }
    [StringLength(50, MinimumLength = 1)]
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

Department.cs

public class Department
{
    public int DepartmentID { get; set; }

    [StringLength(50, MinimumLength = 1)]
    public string Name { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

Category.cs

public class Category
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int CategoryID { get; set; }
    public string Title { 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; }
}

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();
    }
}

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)

首先注意:

您的Administrator实体映射不正确。您将UserId标记为 PrimaryKey ,因此当将实体插入Administrator表时,它会自动将UserId设置为新标识,因此在您的图片中,您会看到UserId逐渐增加。相反,您应将AdminID标记为主键:

[Key]
public int AdminID { get; set; }

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

您还应将User User的UserID标记为主键:

[Key]
public int UserID { get; set; }

第二个注意事项:

您的管理员和用户使用一对多关系映射到故障单,这意味着 1个管理员拥有X故障单,1个用户拥有Y故障。这意味着,Ticket表包含Administrator实体和User实体的外键:图片中的AdminID和UserID。你可以在你的照片上看到它。如果你将TicketId留在这两个类中,那就意味着你有一个一对一关系以及一对多,这真的很奇怪而且不会起作用。因此,您需要从用户和管理员表中完全删除TicketId

第三注:

您还需要从Ticket实体添加对User和Administrator的直接引用,为每个添加[ForeignKey]属性并指定您用作它们的外键的属性。您还需要删除管理员集合,因为如果您这样做,您的关系将多对多

public class Ticket
{
    public int TicketID { get; set; }

    public string Issue { get; set; }

    [DisplayFormat(NullDisplayText = "No Priority")]
    public Priority? Priority { get; set; }

    [ForeignKey("CategoryID")]
    public virtual Category Category { get; set; }
    public int CategoryID { get; set; }

    [ForeignKey("AdminID")]
    public Administrator Admin { get; set; }
    public int AdminID { get; set; }

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

第四注:

您还具有必需 - 用户和管理员之间的可选一对一关系,它以下列方式映射:

您的管理员实体有int UserId,但您的用户实体没有AdministratorId,实体框架将从管理员侧正确映射此关系。如果你像现在这样保持循环引用 - 管理员有UserId而用户有AdministratorId - 它会引起很多问题,因为据我所记得,它不正确地被EF支持。

您应该仔细阅读有关生成数据库架构的Entity Framework文档,否则您将无法将SQL架构转换为正确的EF实体:

实体框架中的数据注释:

https://msdn.microsoft.com/en-us/data/jj591583

使用Fluent API配置/映射属性和类型

https://msdn.microsoft.com/en-us/data/jj591617.aspx