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.