0

I am trying to seed a code first database; in particular a one to many relationship. Whatever combinations of annotations and properties I use I cannot get it to work.

One Course can have many Applicants. I want EF to insert the ApplicantId (identity). I will set CourseId

Models

    //One
    public class Course
    {
        public Course()
        {
            Applicants = new List<Applicant>();
        }
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public string CourseId { get; set; }

        public virtual ICollection<Applicant> Applicants { get; set; }
   }

    //Many
    public class Applicant
    {
        public int ApplicantId { get; set; }

        public string CourseId { get; set; }

        [ForeignKey("CourseId")]
        public virtual Course Course { get; set; } 
    }

Seed

    var course = new Data.Models.Course
    {
          CourseId = "myId",
          Email = "myemail@email.com"
    };

    var applicant =
                new Applicant
               {
                   CourseId = "myId",
                   Forename = "Ryan",
                   Surname = "Giggs"
               };

   course.Applicants.Add(applicant);
   context.Courses.AddOrUpdate(course);

The Id field is required

The models and seed above give me an "Id Field is required" error. I assumed this was because I was not setting the ApplicantId - even though I expected EF to do this for me by convention.

So I tried explicitly setting the ApplicantId...

   var applicant =
                    new Applicant
                   { 
                       ApplicantId = 1,
                       CourseId = "myId",
                       Forename = "Ryan",
                       Surname = "Giggs"
                   };

but got the same error.

Cannot insert the value NULL into column

I then tried explicitly informing EF that ApplicantID is an identity column.

    public class Applicant
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ApplicantId { get; set; }

        //rest as before
    }

But now I get this error:

'ApplicantId', table 'Context1.dbo.Applicant'; column does not allow nulls. INSERT fails.

Note I do not have any code in my modelbuilder since it is my understanding this is only required if model definitions do not follow convention.

EDIT I have created a quick console app which includes just the two models above and the seed method. It works without an issue. I'll therefore try spot a difference between this and the main solution.

Kildareflare
  • 4,590
  • 5
  • 51
  • 65
  • Normally you don't need `[DatabaseGenerated(DatabaseGeneratedOption.Identity)]` if you are using EF CF. Maybe you can try to remove this line? – Mirko Sbr Jun 10 '15 at 08:05
  • Yes, that is what I though. It should work by convention. However, if I remove that line I get the first error - Id Field is required. – Kildareflare Jun 10 '15 at 08:20
  • I think the problem lies within your `AddOrUpdate` method. If you did a basic `Add` on the `DbSet` this code works fine. Could you post the code for the method? – user2697817 Jun 10 '15 at 08:37
  • For troubleshooting, try adding them in separate steps. context.Courses.AddOrUpdate(course); then grab the key applicant.CourseId = course.CourseId then context.Applicants.AddOrUpdate(applicant); You could also try explicitly telling AddOrUpdate what the key is - AddOrUpdate(c => c.CourseId, course) but I doubt that is the issue. – Steve Greene Jun 10 '15 at 13:16
  • @steveGreene Pretty sure I tried that at one point, but I'll give it a shot and let you know. – Kildareflare Jun 10 '15 at 20:15

1 Answers1

0

I have not been able to determine why the validation was failing on seed. As mentioned in the update to the question, I was able to get exactly the same relationship working in a quick console app.

Luckily at present, existing data and prior migrations are not important and thus I was able to delete all migrations and create the database from scratch.

This time around the seed method raised no validation errors and populated the data as expected.

The answer here was useful: How to re-create database for Entity Framework?

In fact, since posting this question, I've had to to this a couple of times. Somehow some of the migrations I am performing are leaving the database in a state which prevents further updates from succeeding.

Community
  • 1
  • 1
Kildareflare
  • 4,590
  • 5
  • 51
  • 65