1到1需要与数据库生成的标识的关系

本文关键字:标识 关系 数据库 | 更新日期: 2023-09-27 18:26:25

我见过很多实现一对一关系的例子,但我的例子失败了,因为需求有所不同(Guid与数据库生成选项、外键属性等)。

我有两个类(Bundesland,Programmkonfiguration),它们有1:1的关系(在商业意义上需要两端),但不能连接到一个表中

对联邦土地的要求:

  • Guid Id为键,但没有DatabaseGenerated属性
  • 导航属性程序配置

Bundesland.cs:

public class Bundesland
{
    [Key]
    public Guid Id { get; set; }
    public virtual Programmkonfiguration Programmkonfiguration { get; set; }
}

Bundesland 的要求

  • Guid Id作为从数据库生成的密钥
  • ForeignKey Property 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; }
} 

数据库模式应该看起来像这个

  • 表Bundesland(Id)
  • 表程序配置(Id,Bundesland_Id)

为什么我失败到现在:

  • 英孚自己并不认识到这种关系
  • 如果我使用属性(ForeignKey,Required)或fluent API,并且模式生成器没有失败,则永远不会在上下文之后设置外键属性Programmkonfiguration.Bundeland_Id。保存更改()

如果你想帮助我,下面是你可能需要的额外课程:https://gist.github.com/anonymous/9cb554cd864e3dbee1ac

我在EF5上使用.NET 4.5(.1),但我在EF6上也失败了

提前感谢:)

1到1需要与数据库生成的标识的关系

您可以为此使用流畅的配置:

public class Bundesland
{
    [Key]
    [ForeignKey("Programmkonfiguration")]
    public Guid Id { get; set; }
    public virtual Programmkonfiguration Programmkonfiguration { get; set; }
}
public class BundesLandConfiguration: EntityTypeConfiguration<Bundesland>
{
    public BundesLandConfiguration()
    {            
        HasProperty(p=>p.Id)
        HasRequired(p=>p.Programmkonfiguration).WithRequiredPrincipal(p=>p.Bundesland);
    }
}
public class Programmkonfiguration
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public Guid Bundesland_Id { get; set; }
    public virtual Bundesland Bundesland { get; set; }
}
public class ProgrammkonfigurationConfiguration: EntityTypeConfiguration<Programmkonfiguration>
{
    public ProgrammkonfigurationConfiguration()
    {
        HasKey(p=>p.Id);
        HasProperty(p=>p.Id)
        HasProperty(p=>p.Bundesland_Id)
    }
}

不要忘记将此配置添加到数据库上下文中的EntityModelConfigurations中。

更新:因为属性命名违反惯例,您应该添加[ForeignKey]属性,就像我添加到Bundesland类的属性Id一样。