Eliemerson Fonseca
Eliemerson Fonseca

Reputation: 757

Allow a foreign key to be null with Entity Type Builder

I need a foreign key to be null, how can I do this with entity configure?

 public void Configure(EntityTypeBuilder<CostCenter> entity)
        {
            entity.ToTable("CostCenter", ApplicationDataContext.DEFAULT_SCHEMA);

            entity.Property(e => e.Id).ValueGeneratedNever();

            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(150)
                .IsUnicode(false);

            entity.Property(e => e.Uid).HasColumnName("UID");

            
            entity.Property(e => e.UpdatedBy)
                .IsRequired()
                .HasMaxLength(250)
                .IsUnicode(false);

            entity.Property(e => e.UpdatedOn).HasColumnType("datetime");

                
                
        }

Now I need to make this attribute that makes it null

entity.HasOne(e => e.Owner)
                .WithMany()
                .HasForeignKey(d => d.OwnerId)
                .HasConstraintName("FK_CostCenter_Account_OwnerId");

Upvotes: 0

Views: 1832

Answers (1)

Harald Coppoolse
Harald Coppoolse

Reputation: 30512

I think that you want to configure that if a CostCenter has a null OwnerId, then the CostCenter does not have an Owner.

Apparently some CostCenters have Owners, and some don't: the Owner is optional. This is a zero-or-one-to-many relationship.

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)
}

It might be that you need to define OwnerId as a nullable property

Upvotes: 1

Related Questions