0

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.

Community
  • 1
  • 1
Peter Smith
  • 5,528
  • 8
  • 51
  • 77
  • To see the 'EntityValidationErrors', check this: http://stackoverflow.com/questions/5345890/getting-exact-error-type-in-from-dbvalidationexception – lightbricko Jun 18 '13 at 11:56
  • Thanks - I've now added that in but I cannot see where the trace output is appearing - where should I see that; it's not in the debug window. Thanks. – Peter Smith Jun 18 '13 at 12:07
  • You're always creating a new user. Are you sure that is what you want? – user1908061 Jun 18 '13 at 12:17
  • @lightbricko I found the problem; the 'real' class has a required field that was not mapped to the database. As soon as I was able to see the validation errors all was solved. Please post as answer so I can give you the points – Peter Smith Jun 18 '13 at 12:20
  • @PeterSmith, I'm glad it's solved. I think you should upvote the answer you found helpful in the link instead, (and then this question can be marked as a duplicate) – lightbricko Jun 18 '13 at 12:24
  • It's not really a duplicate, although that was one step on the way. However I will up vote that one. – Peter Smith Jun 18 '13 at 13:25

1 Answers1

0

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.

Peter Smith
  • 5,528
  • 8
  • 51
  • 77