实体框架外键作为主键代码优先

Nei*_*eil 20 c# entity-framework ef-code-first

我有两个代码第一个模型,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; }
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但是当我尝试将外键添加到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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

Nei*_*eil 36

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

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

    [Required]
    public int State { get; set; }

    public Foo Foo { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 你可以结合[Key,ForeignKey("Foo")] (11认同)
  • 你能用同样流畅的API做同样的事吗? (2认同)