Search code examples
entity-frameworkef-code-firstfluent-interface

EF Code First: Primary Key same as Foreign Key


I have two classes

public class Product
{
    public Guid Id { get; set; }
    public string ProductDetails { get; set; }
}

public class SpecialProductDetails
{
    public Guid Product_Id { get; set; } // PK and FK to Product class
    public string SpecialName { get; set; }
    public string SpecialDescription { get; set; }

    public virtual Product Product { get; set; }
}

SpecialProductDetails is mapped 1-1 with Product class and is optional. It shares the same PrimaryKey and ForeignKey.

In Fluent API i am mapping this relationship like this (inside SpecialProductDetails)

public SpecialProductDetails()
{
    HasKey(p => p.Product_Id);
    HasRequired(p => p.Product).WithMany().HasForeignKey(p => p.Product_Id).WillCascadeDelete(true);
}

This gives me this error when trying to generate the Database

\tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'SpecialProductDetails_Product_Source' in relationship 'SpecialProductDetails_Product_Source'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'.

How can i have a column set as PK and FK on EF Code First?


Solution

  • I'm quite sure you have already solved that, but I hit the same problem and the solution I found was:

     public SpecialProductDetails()
        {
            HasKey(p => p.Product_Id);
            HasRequired(p => p.Product).WithOptional();
        }
    

    "it worth noting that when we are mapping a one-to-one association with fluent API, we don't need to specify the foreign key as we would do when mapping a one-to-many association with HasForeignKey method. Since EF only supports one-to-one associations on primary keys, it will automatically create the relationship in the database on the primary keys."

    after http://weblogs.asp.net/manavi/associations-in-ef-4-1-code-first-part-3-shared-primary-key-associations