Question

I am using Visual Studio 2010, C# 4.0 and Entity Framework 5.0.

My (simplified) models are:

public class Case
{
    public int CaseID { get; set; }
    public int CaseStatusID { get; set; }
    public DateTime DateOfNotification { get; set; }        

    public User User { get; set; }

    public Case()
    {                  
    }
}

public class User
{
    public int UserID {get;set;}
    public string Name { get; set; }

    public Case Case { get; set; }

    public User()
    {
    }
}

The data context is:

public class DataContext : DbContext
{
    public DbSet<Case> Cases { get; set; }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Case>()
           .HasKey(m => m.CaseID)
           .Property(m => m.CaseID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        modelBuilder.Entity<Case>()
            .HasRequired(m => m.User)
            .WithRequiredPrincipal(m => m.Case);
    }
}

And I am seeding the database with:

protected override void Seed(DataContext context)
    {
        Case Case = new Case();
        Case.CaseStatusID = 1;
        Case.DateOfNotification = DateTime.Today;

        Case.User = new User();

        Case.User.UserID = Case.CaseID;
        Case.User.UsersFamilyNameEnc = "Smith";
        Case.User.UsersGivenNameEnc = "Petra";

        context.Cases.AddOrUpdate(Case);         
        context.SaveChanges();
    }

Using Migrations with no seed the database deploys with no errors and I can populate the database manually.

If I comment out the User class the database seeds correctly.

THE PROBLEM

As soon as I add the user relationship and run the migration command I get this error

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

I cannot see the EntityValidationErrors and any break points and not reached.

The problem seems to be in the relationship. I have tried different ways of specifying this but the result is always the same.

THE ANSWER

Getting exact error type in from DbValidationException was the first part of the solution - understanding the error. I then needed to add

catch (DbEntityValidationException dbEx)
{
    StringBuilder sb = new StringBuilder();

    foreach (var validationErrors in dbEx.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
            sb.AppendFormat("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
        }
    }
    throw new Exception(sb.ToString());
}

(an amalgm of two other answers) with a try to get the errorto the Package Manager console.

Finally, I found that my 'real' model contained the following:

[NotMapped]
[Required(ErrorMessage = "The family name/surname is required")]
[Display(Name = "Family name/surname")]
public string UserName { get; set; }

I thought that the NotMapped would exclude the field but the Required seems to override this. Once I put in a value for this it all started working.

Was it helpful?

Solution

Please see the comments on the question above. There were a series of steps needed to solve this.

  1. Displaying the validation errors - the solution referred to above by lightbricko enabled the errors to be retrieved but they did not display in the PM console
  2. This was achieved by adding the stringbuilder to code displayed above and then throwing that as a new exception
  3. Finally that showed that a field that was not mapped to the database was still validated as part of the seed process

A bit of a journey but got there finally - thanks for all the help on the way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top