我有两个代码第一个模型,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并说明状态,如果我想改变它的状态,就不必从数据库中检索整个Foo对象。
我应该如何首先使用EF代码进行设置?
答案 0 :(得分:32)
我以为我会给它一个镜头并且效果很好。
public class FooState
{
[Required]
[Key]
[ForeignKey("Foo")]
public int FooStateId { get; set; }
[Required]
public int State { get; set; }
public Foo Foo { get; set; }
}