Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Foreign Key as Primary Key Code First

Tags:

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?

like image 293
Neil Avatar asked Jan 31 '13 10:01

Neil


1 Answers

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; } } 
like image 122
Neil Avatar answered Oct 06 '22 14:10

Neil