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, with FooState being an optional part of Foo.

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 is successful, but when I attempt to add the foreign key to FooState as shown

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; }
}

Because FooStateId actually uses FooId as its primary key, everything collapses. From the perspective of a database, this makes sense.

However, I would prefer to keep the necessary attribute while not having to populate an instance of Foo when storing the FooState record.

As a result, if I wanted to alter the state of a Foo object, I could send down a FooId and state instead of having to retrieve the entire Foo object from the database.

How should I initially build this up using EF code?

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

Accepted Answer

I decided to try this, and it turned out to work well.

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