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

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

问题描述

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

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.

我试过:

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

我记得努力让这个在核心EF前工作。

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

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

Is this possible? How do I configure the entity?

推荐答案

是的,您可以使用EF Core执行此操作,默认情况下创建为唯一索引作为过滤索引(WHERE ... IS NOT NULL)

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天全站免登陆