Pilouk
Pilouk

Reputation: 1317

EF CORE 2.0 Incompatible relationship (nullable foreign key)

In our businessslogic we have some contacts row that may have a relationship with one billing row (0..N).

Here the contact class

    public class ESUsersContact
{
    [Key]
    public int Id { get; set; }

    [ForeignKey("Billing")]
    public int? BillingId { get; set; }

    public string Title { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }
    public string City { get; set; }
    public string PostalCode { get; set; }
    public string Phone { get; set; }
    public string CellPhone { get; set; }
    public string Fax { get; set; }

    public ES.Enums.BusinessESCommon.Language.AllLanguage Language { get; set; }

    public virtual ICollection<ESUsersCompany> Companies { get; set; }

    public virtual ESUsersBilling Billing { get; set; }


}

Here is the billing class

    [Key, Column(Order = 0)]
    [ForeignKey("Company")]
    public int CompanyId { get; set; }

    [Key, Column(Order = 1)]
    public ES.Enums.BusinessESUsers.Billing.Type Type { get; set; }

    public ES.Enums.BusinessESUsers.Billing.Payment PaymentType { get; set; }
    public ES.Enums.BusinessESUsers.Billing.Frequency PaymentFrequency  { get; set; }

    public decimal Amount { get; set; }

    public bool IsFreeTrial { get; set; }

    public DateTime FreeTrialEndDate { get; set; }

    public DateTime? NextPaymentDate { get; set; }

    public virtual ESUsersCompany Company { get; set; }

    public virtual ICollection<ESUsersContact> Contacts { get; set; }
}

However, I receive this error doing so.

The relationship from 'ESUsersContact.Billing' to 'ESUsersBilling.Contacts' with foreign key properties {'BillingId' : Nullable<int>} cannot target the primary key {'CompanyId' : int, 'Type' : Type} because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.

I don't understand why the error occurs and state the primary key {'CompanyId' : int, 'Type' : Type}.

Upvotes: 0

Views: 1954

Answers (1)

Seraf&#237;n
Seraf&#237;n

Reputation: 132

ESUsersContact.Billing class has a composite key. ESUsersContact has to map both of the foreign keys. CompanyId and Type. You can not refer only one column since ESUsersContact.Billing has two columns for the key.

Upvotes: 3

Related Questions