![](/img/trans.png)
[英]Duplicating record in Entity Framework many to many relationship using Asp.net Boilerplate
[英]Entity Framework 1-to-1 relationship with ASP.NET Boilerplate
当我们使用ASP.NET Boilerplate时,如何设置与以下模型的 1:1 关系? 提前致谢。
注 1:我已经看到了关于 EF 1 对 1 关系的好答案。 但遗憾的是,我不知道如何使用 ASP.NET Boilerplate 进行设置,因为 PK 是由 ABP 自动设置的。 在我的场景中,两个表都有int
PK。
注 2:这里, Property
和Address
模型具有 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; }
}
关系映射应该在OnModelCreating
方法中完成。 您的 DbContext 类将位于 EntityFramework 文件夹下的 EntityFramework 项目中。
您可以使用以下内容:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Property>().HasRequired(e => e.Address).WithOptional(e => e.Property);
}
如果Address
的Property
属性不应为 null,则.WithOptional()
方法可以替换为WithRequiredDependent()
或WithRequiredPrincipal()
,具体取决于用例。
另一个解决方案:
您不会在 EF7 中找到 HasOptional 等效方法。 按照惯例,如果您的 FK 属性可为空,则您的导航属性将被视为可选
modelBuilder.Entity<Blog>()
.HasOne(p => p.Document)
.WithOne(i => i.CancelNote)
.HasForeignKey<Document>(b => b.CancelNoteForeignKey);
关于您的第二个问题,EF Core (EF7) 不支持延迟加载。 在此链接中,您将找到加载相关实体的选项
PS:请使用您自己的实体名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.