【发布时间】:2014-10-14 15:39:16
【问题描述】:
我见过很多实现一对一关系的示例,但我的做法失败了,因为要求有些不同(Guid 与数据库生成的选项、外键属性等)。
我有 2 个类(Bundesland、Programmkonfiguration)具有 1:1 的关系(从业务角度来说,两端都是必需的)但不能合并到一个表中
对德州的要求:
- Guid Id 作为键但没有 DatabaseGenerated 属性
- 导航属性程序配置
Bundesland.cs:
public class Bundesland
{
[Key]
public Guid Id { get; set; }
public virtual Programmkonfiguration Programmkonfiguration { get; set; }
}
对德州的要求
- Guid ID 作为从数据库生成的密钥
- ForeignKey 属性 Bundesland_Id(接口需要带 _)
- Navigation Property Bundesland
程序配置.cs:
public class Programmkonfiguration
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Guid Bundesland_Id { get; set; }
public virtual Bundesland Bundesland { get; set; }
}
数据库架构应如下所示
- 表德国 (Id)
- 表程序配置(Id,Bundesland_Id)
为什么我到现在都失败了:
- EF 无法自行识别关系
- 如果我使用属性(ForeignKey,Required)或 fluent API 并且模式构建器没有失败,则在 context.SaveChanges() 之后,永远不会设置外键属性 Programmkonfiguration.Bundesland_Id
如果您想帮助我,您可能需要以下其他课程:https://gist.github.com/anonymous/9cb554cd864e3dbee1ac
我将 .NET 4.5(.1) 与 EF5 一起使用,但我在 EF6 上也失败了
提前致谢:)
【问题讨论】:
标签: c# entity-framework ef-code-first