【问题标题】:Entity Framework - how to set column as unique related to another column实体框架 - 如何将列设置为与另一列相关的唯一列
【发布时间】:2020-03-30 14:42:37
【问题描述】:

我正在使用实体框架,并且我有以下模型类:

public class Test 
{
    public string Name { get; set; }
    public int SiteId { get; set; }    
    public bool IsPrimary { get; set; } 
}

如何根据SiteIdIsPrimary 列设置为唯一?

例如,我可以将多个记录设置为同一SiteIdIsPrimary 为假,但只有一个设置为真。

【问题讨论】:

标签: asp.net asp.net-mvc entity-framework asp.net-core


【解决方案1】:

终于找到解决办法了!当 isPrimary 为 false 时,我可以为同一个 siteId 设置多行,但当 isPrimary 为 true 时,只有一行。

modelBuilder.Entity<MyTable>()
            .HasIndex(b => new { b.IsPrimary, b.SiteId })
            .IsUnique()
            .HasFilter("IsPrimary = 1"); 

【讨论】:

    【解决方案2】:

    您可以尝试以下代码:

    [Index("Index_SiteId_IsPrimary", 1, IsUnique = true)]
    public int SiteId  { get; set; }
    
    [Index("Index_SiteId_IsPrimary", 2, IsUnique = true)]
    public bool IsPrimary { get; set; }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-23
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-24
      相关资源
      最近更新 更多