Does EF Core allow a unique column to contain multiple nulls?

c# ef-code-first entity-framework entity-framework-core

Question

My entity has a property which is allowed to be null. BUT, if it isn't null, then it must be unique. In other words, the column is unique but allows multiple nulls.

I've tried:

config.Property(p => p.ProductId).IsRequired(false);

I remember struggling to get this to work in pre-Core EF.

Is this possible? How do I configure the entity?

1
7
1/3/2017 8:39:04 AM

Accepted Answer

Yes, you can do that with EF Core, as a Unique index by default is created as a filtered index (WHERE ... IS NOT NULL)

config.Entity<Product>()
        .HasIndex(b => b.ProductId)
        .IsUnique();

https://github.com/aspnet/EntityFramework/pull/2868

12
1/3/2017 8:58:55 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow