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?
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With