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

.net c# entity-framework entity-framework-6 sql-server

Accepted Answer

Conventionally, EF6 uses the so-called Association for Shared Primary Keys representation of one-to-one connections, where the PK of the dependent entity likewise acts as the principal entity's FK.

In your situation, it takes intoAccount.Id to act as the FKCustomer , and since it was created automatically, you received the relevant exception.

Another issue is that EF6 does not enable one-to-one relationships with explicit FK properties (there is no such thing as explicit FK property in EF6).HasForeignKey one-to-many relationships-like fluent API).

Therefore, you must delete theAccountId remove everything except the navigation attribute from the model. Additionally, even if it is not absolutely required, it would be wise to adhere to the name rules and just call itAccount instead ofAccountValue .

Otherwise, substitute

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

public virtual Customer CustomerValue { get; set; }

with

public virtual Customer Customer { get; set; }

utilising the FK column name may be specifiedMapKey a fluid API

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

You're done now.

This now appropriately adds a new line after the previous one.Customer after which a newAccount mentioning it

var account = new Account
{
    AccountNumber = "00123456",
    Customer = new Customer { FirstName = "Joe" }
};
db.Accounts.Add(account);
db.SaveChanges();
5
4/27/2018 3:42:14 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow