user2055119
user2055119

Reputation: 19

entity framework foreign key where dependent key is not the primary key

I have two tables, the dependent table has a foreign key which is not the primary key. This is a 0 to 1 relationship. How do I set up the association with entity framework 6, code first, fluent API? The tables already exist in the db.

public class Formula
{
    public int Id { get; set; } /*Primary key*/
    public string Name { get; set; }
}

public class MayHaveAFormula
{
    public int Id { get; set; } /*Primary key*/
    public int? FormulaId { get; set; } /*links to Formula.Id */
    public Formula Formula { get; set; }
}

Upvotes: 1

Views: 590

Answers (1)

Gert Arnold
Gert Arnold

Reputation: 109099

This is a 0 to 1 relationship

No, it isn't. You want it to be, but it is a one-to-many relationship. When an entity has an independent foreign key (i.e. not also being its primary key) you can't model it as a 1:1 association in EF.

So you model this as a regular 1:n association and in business logic you enforce it's 1:1.

On thing you can do to help enforce 1:1 is to create a unique index on the FormulaId field. Now the database will throw an ugly exception when you try to create a second MayHaveAFormula for a Formula. Of course this shouldn't replace business logic, but it's an extra safeguard.

Upvotes: 1

Related Questions