C# 实体框架外键作为主键代码优先
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14623342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity Framework Foreign Key as Primary Key Code First
提问by Neil
I have two code first models, Foo and FooState where Foo has an optional FooState.
我有两个代码优先模型,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; }
}
This works fine however when I try to add the foreign key to FooState like so
但是,当我尝试将外键添加到 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; }
}
It all falls over because FooStateId is really using FooId as it's primary key. This makes sense from a database point of view.
这一切都失败了,因为 FooStateId 确实使用 FooId 作为它的主键。从数据库的角度来看,这是有道理的。
I would however like not to have to populate an instance of Foo when saving the FooState record but still retain the required attribute.
但是,我希望在保存 FooState 记录时不必填充 Foo 实例,但仍保留所需的属性。
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.
这将允许我在 dto 中发送 FooId 和状态,如果我想更改其状态,则不必从数据库中检索整个 Foo 对象。
How should I be setting this up with EF code first?
我应该如何首先使用 EF 代码进行设置?
采纳答案by Neil
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; }
}