Entity Framework - One-to-One - ReferentialConstraint is mapped to a store-generated column

前端 未结 1 624
清歌不尽
清歌不尽 2020-12-20 03:31

I have what should be a simple one-to-one relationship to create within EF. But I\'m receiving the following error when I try to insert:

ReferentialCo

相关标签:
1条回答
  • 2020-12-20 04:19

    By convention EF6 represents the one-to-one relationships using the so called Shared Primary Key Association, where the PK of the dependent entity also serves as FK to the principal entity.

    In your case, it considers Account.Id to be the FK to Customer, and since it's auto-generated, you get the exception in question.

    The additional problem is that EF6 does not support one-to-one relationship with explicit FK property (there is no HasForeignKey fluent API similar to one-to-many relationships).

    So you need to remove the AccountId property from the model and leave only the navigation property. Also, although not strongly necessary, it would be good to follow the naming conventions and just call it Account rather than AccountValue.

    In other words, replace

    [Column("CUSTOMER_ID")]
    public int? CustomerId { get; set; }
    
    public virtual Customer CustomerValue { get; set; }
    

    with

    public virtual Customer Customer { get; set; }
    

    The FK column name can be specified using the MapKey fluent API:

    modelBuilder.Entity<Customer>()
        .HasRequired(c => c.Account)
        .WithRequiredPrincipal(a => a.Customer)
        .Map(m => m.MapKey("CUSTOMER_ID")); // <--
    

    And you are done.

    Now the following correctly inserts first a new Customer and then a new Account referencing it:

    var account = new Account
    {
        AccountNumber = "00123456",
        Customer = new Customer { FirstName = "Joe" }
    };
    db.Accounts.Add(account);
    db.SaveChanges();
    
    0 讨论(0)
提交回复
热议问题