Note that there are some explanatory texts on larger screens.

plurals
  1. POOne-To-One Entity Framework Code-First Mapping With Composite Keys
    primarykey
    data
    text
    <p>Is it possible to create a one-to-one relationship on already defined entity properties? I've got the following entities:</p> <pre><code>public class Asset { public int AssetId { get; set; } public int OwningCustomerId { get; set; } public virtual Customer OwningCustomer { get; set; } } public class CustomerAsset { public int CustomerId { get; set; } // Primary key 0 public int AssetId { get; set; } // Primary key 1 public int CustomerAssetStatusId { get; set; } public string Name { get; set; } public virtual Customer Customer { get; set; } public virtual Asset Asset { get; set; } } </code></pre> <p>CustomerAsset represents various states of ownership of an asset. Although the same AssetId can exist multiple times in this table, there will only ever be one instance where CustomerAssetStatusId = 1. In order to have quick access to the asset's current owner, I also maintain OwningCustomerId in the Asset table.</p> <p>I would like to have a navigation property from Asset to CustomerAsset called OwningCustomerAsset. This is a one-to-one relationship. Unfortunately, I don't know how to define it since the foreign key fields are already defined in Asset. Typically, I would create a relationship like this on Asset:</p> <pre><code>HasRequired(e =&gt; e.OwningCustomerAsset).WithRequiredDependent().Map(m =&gt; m.MapKey("OwningCustomerId", "AssetId")); </code></pre> <p>Of course this results in the following error: "Each property name in a type must be unique. Property name 'OwningCustomerId' was already defined."</p> <p>How can I tell EF that OwningCustomerId/AssetId is the foreign key to CustomerAsset?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload