【问题标题】:Entity Framework 1-to-1 relationship with ASP.NET Boilerplate实体框架与 ASP.NET 样板的一对一关系
【发布时间】:2016-02-02 03:59:21
【问题描述】:

当我们使用ASP.NET Boilerplate时,如何设置与以下模型的1:1关系?提前致谢。

注意 1: 我已经看到 this nice answer 关于 EF 一对一的关系。但不幸的是,我不知道如何使用 ASP.NET Boilerplate 进行设置,因为 PK 是由 ABP 自动设置的。在我的场景中,两个表都有int PK。

注意 2:这里,PropertyAddress 模型具有 1:1 的关系。

Property模型

[Table("IpProperties")]
public class Property : FullAuditedEntity
{
    public virtual bool Vacant { get; set; }

    public virtual Address Address { get; set; }
}

Address模型

[Table("IpAddresses")]
public class Address : FullAuditedEntity
{ 
    [Required]
    [MaxLength(MaxLength)]
    public virtual string StreetNumber { get; set; }

    public virtual Property Property { get; set; }
}

【问题讨论】:

    标签: c# asp.net-mvc-5 ef-code-first entity-framework-6 asp.net-boilerplate


    【解决方案1】:

    关系映射应在 DbContext 的 OnModelCreating 方法中完成。您的 DbContext 类将位于 EntityFramework 文件夹下的 EntityFramework 项目中。

    你可以使用类似下面的东西:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<Property>().HasRequired(e => e.Address).WithOptional(e => e.Property);
    }
    

    如果AddressProperty 属性不应为null,则.WithOptional() 方法可以替换为WithRequiredDependent()WithRequiredPrincipal(),具体取决于用例。

    另一种解决方案:

    ABP forum - REFERENTIAL INTEGRITY ISSUE - ONE TO ONE RELATIONSHIP

    【讨论】:

    • 感谢您的支持:)
    【解决方案2】:

    在 EF7 中找不到 HasOptional 等效方法。按照惯例,如果您的 FK 属性可以为空,您的导航属性将被视为可选

     modelBuilder.Entity<Blog>()
                    .HasOne(p => p.Document)
                    .WithOne(i => i.CancelNote)
                    .HasForeignKey<Document>(b => b.CancelNoteForeignKey);
    

    关于第二个问题,EF Core (EF7) 不支持延迟加载。在此链接中,您将找到加载相关实体的选项

    PS:请使用您自己的实体名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多