Entity Framework Foreign Key as Primary Key Code First

c# ef-code-first entity-framework

Question

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?

1
20
1/31/2013 10:17:16 AM

Accepted Answer

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; }
}
36
1/31/2013 10:17:16 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow