Neil
Neil

Reputation: 5239

Entity Framework Foreign Key as Primary Key Code First

I have two code first models, Foo and FooState where Foo has an optional FooState.

public class Foo
{
    [Key]
    public int FooId { get; set; }

    public FooState FooState { get; set; }
}

public class FooState
{
    [Key]
    public int FooStateId { get; set; }

    [Required]
    public int State { get; set; }

    [Required]
    public Foo Foo { get; set; }
}

This works fine however when I try to add the foreign key to FooState like so

public class FooState
{
    [Key]
    public int FooStateId { get; set; }

    [Required]
    public int State { get; set; }

    [ForeignKey("Foo")]
    [Required]
    public int FooId
    public Foo Foo { get; set; }
}

It all falls over because FooStateId is really using FooId as it's primary key. This makes sense from a database point of view.

I would however like not to have to populate an instance of Foo when saving the FooState record but still retain the required attribute.

This would allow me to send down a FooId and state in a dto and not have to retrieve the whole Foo object from the DB if I want to make a change to its state.

How should I be setting this up with EF code first?

Upvotes: 24

Views: 28828

Answers (1)

Neil
Neil

Reputation: 5239

I thought I'd give this a shot and it worked nicely.

public class FooState
{
    [Required]
    [Key]
    [ForeignKey("Foo")]
    public int FooStateId { get; set; }

    [Required]
    public int State { get; set; }

    public Foo Foo { get; set; }
}

Upvotes: 45

Related Questions