0

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");
Eliemerson Fonseca
  • 717
  • 3
  • 10
  • 33
  • Possible duplicate of [How to get Entity Framework Code First and nullable foreign key properties to work?](https://stackoverflow.com/questions/5189701/how-to-get-entity-framework-code-first-and-nullable-foreign-key-properties-to-wo) – devlin carnate May 30 '19 at 19:11

1 Answers1

1

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

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • When I using HasOptional, It's not property – Eliemerson Fonseca May 31 '19 at 17:01
  • I cannot find method HasOption in the EntityTypeBuilder – Bui Quang Huy Jun 10 '19 at 04:01
  • 1
    Full Entity framework DbContext, has method OnModelCreating with a parameter of type DbModelBuilder. this has a property Entity of type EntityTypeConfiguration which has method [HasOptional](https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.modelconfiguration.entitytypeconfiguration-1.hasoptional?view=entity-framework-6.2.0). Using entity framework core? Visit [Equivalent for HasOptional in EF Core](https://stackoverflow.com/questions/35562483/equivalent-for-hasoptional-in-entity-framework-core-1-ef7) – Harald Coppoolse Jun 11 '19 at 09:29