C# 使用实体类型生成器允许外键为null
我需要一个外键为null,如何使用EntityConfigure实现这一点C# 使用实体类型生成器允许外键为null,c#,entity-framework,C#,Entity Framework,我需要一个外键为null,如何使用EntityConfigure实现这一点 public void配置(EntityTypeBuilder实体) { ToTable(“成本中心”,ApplicationDataContext.DEFAULT\u模式); Property(e=>e.Id).ValueGeneratedNever(); entity.Property(e=>e.Name) .IsRequired() .HasMaxLength(150) .IsUnicode(假); Proper
public void配置(EntityTypeBuilder实体)
{
ToTable(“成本中心”,ApplicationDataContext.DEFAULT\u模式);
Property(e=>e.Id).ValueGeneratedNever();
entity.Property(e=>e.Name)
.IsRequired()
.HasMaxLength(150)
.IsUnicode(假);
Property(e=>e.Uid).HasColumnName(“Uid”);
属性(e=>e.UpdatedBy)
.IsRequired()
.HasMaxLength(250)
.IsUnicode(假);
Property(e=>e.updateOn).HasColumnType(“datetime”);
}
我认为您需要配置,如果成本中心
的OwnerId为空,那么成本中心
就没有所有者
显然,一些成本中心
拥有所有者
,而一些没有:所有者
是可选的。这是一种零或一对多的关系
public void Configure(EntityTypeBuilder<CostCenter> costCenterEntity)
{
...
costCenterEntity.HasOptional(costCenter => costCenter.OwnerId) // The owner is optional
.WithMany(owner => owner.CostCenters) // the owner has zero or more CostCenters
.HasForeignKey(costCenter => costCenter.OwnerId)
}
public void配置(EntityTypeBuilder costCenterEntity)
{
...
costCenterEntity.HasOptional(costCenter=>costCenter.OwnerId)//所有者是可选的
.WithMany(owner=>owner.CostCenters)//所有者拥有零个或多个CostCenters
.HasForeignKey(costCenter=>costCenter.OwnerId)
}
可能是您需要将OwnerId定义为一个可为空的属性当我使用HasOptional时,它可能是重复的,它不是property。我在EntityTypeBuilderFull实体框架DbContext中找不到方法HasOption,has方法OnModelCreating带有DbModelBuilder类型的参数。这有一个EntityTypeConfiguration类型的属性实体,该实体具有方法。使用实体框架核心?参观