EF Code First – Be careful how you define keys

25. January 2011 Uncategorized 0

Today I was working on a project that is using EF Code First for its DAL. I was moving records from one database to another, and there was one table in particular that I needed to update that had a compound key (GroupId and LeadId.) I created the object and then went into model builder and added the following lines of code to map out my keys:

modelBuilder.Entity<GroupedLead>().HasKey(g => g.GroupId);     
modelBuilder.Entity<GroupedLead>().HasKey(g => g.LeadId);

 The problem was, when I would do a

context.SaveChanges()

I’d get an error saying “A value of NULL cannot be inserted into column LeadId.”

I checked, and double checked, and both GroupId and LeadId had valid values. Turns out it’s a mapping problem. My mapping should have been:

modelBuilder.Entity<GroupedLead>().HasKey(g => new { g.GroupId, g.LeadId });  </code>