0
votes

I'm using EntityFramework via DbContext and an Exisiting Database.

When I Add an Order entity to my context and call SaveChanges(), I'm encountering an exception of: "A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: OrderId".

I believe this is happening because of the composite key on my OrderAddress table and I'm hoping there is a way around it...I don't want to create an IDENTITY on that table.

Here are my entities, simplified...

// OrderId is an IDENTITY PK
public class Order
{
     public int OrderId { get; set; }
     public IList<OrderAddress> Addresses { get; set; }
     public int Total { get; set; }
}

// PK on this table is composite key of OrderId and OrderAddressTypeId
public class OrderAddress
{
     public int OrderId { get; set; }
     public int OrderAddressTypeId { get; set; }
     public string Address { get; set; }
}

Here is my Context, simplified...

public class StoreContext : DbContext
{
     DbSet<Order> Orders { get; set; }
     DbSet<OrderAddress> OrderAddresses { get; set; }

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
          // Set the Identity for Order
          modelBuilder.Entity<Order>()
               .Property(x => x.OrderId)
               .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

          // Set composite key for Order Address
          modelBuilder.Entity<OrderAddress>()
               .HasKey(x => new { x.OrderId, x.OrderAddressTypeId });
     }
}

NOTE: I've looked at the other SO questions that are similar and tried the solutions listed with no success. I've verified that my foreign keys are setup correctly in the database. What's different about my question is the use of the composite key.

Thanks in advance for the help.

UPDATE:

This ended up not being related to the composite key at all. There was an additional line in my Context OnModelCreating method that required a child entity, OrderSummary, which is based on a View in my database. The line looked like this...

modelBuilder.Entity<OrderSummary>().HasRequired(x => x.Order).WithRequiredPrincipal(x => x.OrderSummary);

I had never intended for OrderSummary to be a required principal of Order. Changing it to the following fixed the problem...

modelBuilder.Entity<OrderSummary>().HasRequired(x => x.Order);

Unfortunately, the error message from EF was not very specific and lead me on a wild good chase.

Thanks for looking.

1

1 Answers

1
votes

This error says that some OrderId property (the exception should contain information about the entity or relation where this happens) is mapped as store generated = it has DatabaseGeneratedOption set to Identity or Computed. If the issue is related to OrderAddress entity try to add this to your mapping definition:

modelBuilder.Entity<OrderAddress>()
            .Property(x => x.OrderId)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);