EF Core 是否允许唯一列包含多个空值? [英] Does EF Core allow a unique column to contain multiple nulls?

查看:35
本文介绍了EF Core 是否允许唯一列包含多个空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实体有一个允许为空的属性.但是,如果它不为空,那么它必须是唯一的.换句话说,该列是唯一的,但允许多个空值.

我试过了:

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

我记得努力让它在预核心 EF 中工作.

这可能吗?如何配置实体?

解决方案

是的,您可以使用 EF Core 做到这一点,因为默认情况下,唯一索引创建为过滤索引(WHERE ... IS NOT NULL)

>

config.Entity().HasIndex(b => b.ProductId).是独特的();

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

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?

解决方案

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

这篇关于EF Core 是否允许唯一列包含多个空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆