entity framework外键作为主键代码优先

我有两个代码第一个模型,Foo和FooState,其中Foo有一个可选的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; } } 

这工作正常,但是当我尝试将外键添加到FooState时

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

这一切都失败了,因为FooStateId确实使用FooId作为它的主键。 从数据库的角度来看,这是有道理的。

但是,我希望在保存FooState记录时不必填充Foo的实例,但仍保留必需的属性。

这将允许我在dto中发送一个FooId和state,如果我想对其状态进行更改,则不必从DB中检索整个Foo对象。

我应该如何首先使用EF代码进行设置?

我以为我会给它一个镜头,它很好用。

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