Unknown's avatar

Configure 1:1 relationship in code first

When I tried to load some test data into a database I’d just created in code first I hit the following error:

“a dependent property in a referential constraint is mapped to a store-generated column. column ‘id’

Example loading code:

   1:  myDbContext.Accounts.Add(
   2:     new Accounts{
   3:         Name = "Account #1",
   4:                 ReferenceData = new Entity2
   5:                                     {
   6:                                        RefLocator = "Ref #1"
   7:                                      }
   8:                 })

I eventually configured the POCO classes for the two entities as follows:
   1:  namespace Test.Model
   2:  {
   3:      [Table("Account")]
   4:      public class Account
   5:      {
   6:          [Key, ForeignKey("ReferenceData")]
   7:          public Guid Id { get; set; }
   8:          public string Name { get; set; }
   9:          public ReferenceData ReferenceData { get; set; }
  10:   
  11:      }
  12:      [Table("ReferenceData")]
  13:      public class ReferenceData
  14:      {
  15:          [Key, ForeignKey("Account")]
  16:          public Guid Id { get; set; }
  17:          public string RefLocator { get; set; }
  18:   
  19:   
  20:      }
  21:  }

I tend to prefer using attributes to the fluent mapping when writing EF classes. 
Hopefully this saves someone a little time.

Leave a comment