0

After trying to update my database using update-database I get an EntityValidationError with one line number(33) where there's the error and a bunch of text I can't interpret. I don't have enough information nor do I have enough knowledge in order to fix this issue. Is it related to my classes/Context or my configuration being incorrect as there's not a single error showing in the code.

I don't know what I'm doing wrong because this worked when I only had users,categories and tickets classes.

Configuration.cs

internal sealed class Configuration : DbMigrationsConfiguration<RecreationalServicesTicketingSystem.DAL.IssueContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
        }

        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();   <----LINE 33




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




            };
            departments.ForEach(s => context.Departments.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 = 2,DepotID =2 },

    };

            users.ForEach(s => context.Users.AddOrUpdate(p => p.LastName, 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 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"),
                    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();





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

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


        }
    }

Department.cs

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

        [StringLength(50, MinimumLength = 3)]
        public string Name { get; set; }

        public virtual ICollection<User> Users { 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; }
        //Setting up relationships A use can apply for any number of tickets, so Tickets is defined as a collection of Ticket entities.
        public virtual ICollection<Ticket> Users { 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; }

}

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

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

Ticket.cs

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

}

enter image description here

TykiMikk
  • 1,058
  • 3
  • 15
  • 31
  • Possible duplicate of [Validation failed for one or more entities. See 'EntityValidationErrors' property for more details](http://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert) – gunr2171 Mar 02 '16 at 02:13
  • More readable = less details? – Ian Mar 02 '16 at 02:15
  • @gunr2171 Tried all those methods and none of them worked. – TykiMikk Mar 02 '16 at 02:16
  • Then it is quite subjective I think... The error you see is typical for any error and by far is considered best way to show the source of error. If you define your own custom error, perhaps you can read it, but you cannot trace the source of the error - thus unable to fix it. – Ian Mar 02 '16 at 02:18
  • @Ian I tried using Try catch with using System.Data.Entity.Validation;. It's really annoying how the entity error doesn't point to a class or anything. context.SaveChanges() doesn't really tell me much but that saving my data onto the database didn't work. – TykiMikk Mar 02 '16 at 02:21
  • @JasonWan As for the specific for EF, honestly I am not too sure also how it actually works since there are many layers in it not-transparent to us. Nevertheless, my point is making it more human readable may not necessarily resulting in finding the issue. On the contrary, it may make us unable to find it. Maybe you should rather ask, "what error does this mean in EF" or "how to debug it" - something along that line. ;) – Ian Mar 02 '16 at 02:24
  • @Ian Thanks I'll use your suggestion. – TykiMikk Mar 02 '16 at 02:26

1 Answers1

1

Its failing validation because you have a minimum string length of 3 for you department name, and the first one you create is only two characters long: "IT".

Hth

wazdev
  • 323
  • 4
  • 11
  • Man that was stupid. Now i have this error `System.Data.SqlClient.SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.User_dbo.Department_DepartmentID". The conflict occurred in database "RecreationalServicesTicketingSystem.DAL.IssueContext", table "dbo.Department", column 'DepartmentID'.` – TykiMikk Mar 02 '16 at 02:44
  • Is the a reason why you are using the fluent syntax in onmodelcreating of your issues context to construct relationships between entities rather than just using a many to many mapping in your model definitions? – wazdev Mar 02 '16 at 02:50
  • Well I'm following a tutorial here http://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/creating-a-more-complex-data-model-for-an-asp-net-mvc-application and the reason why I use it is because I'll know what the numbers in the column are talking about. I'm not very confident I can code it using many to many mapping. You're very welcome to try. I've uploaded the classes and entity diagrams. – TykiMikk Mar 02 '16 at 03:03
  • 2
    @JasonWan great. Seems like you get your answer. ;) – Ian Mar 02 '16 at 03:15
  • This may because you are inserting a user object without a departmentid reference. Hence violating the FK constraint. – wazdev Mar 02 '16 at 03:20
  • @wazdev So if you look at the updated Configuration.cs under var user = new List I enter DepartmentID = 1 and DepotID =1 but it's still the same error. My guts tell me it's my relational database that is the problem. I think my mapping isn't what I wanted and I don't have enough knowledge to fix it. – TykiMikk Mar 02 '16 at 03:27
  • @JasonWan have you looked at the database in SQL Server Management Studio? Is there any data in the Depot, Department, User tables etc? – wazdev Mar 02 '16 at 04:08
  • @wazdev That's the thing. I haven't migrated once because of all these errors so I don't think they will be any data in my tables. – TykiMikk Mar 02 '16 at 04:46