【问题标题】:Entity Framework (Core), Unique "Composite Columns" that are not the Key实体框架(核心),不是关键的唯一“复合列”
【发布时间】:2018-09-26 18:20:25
【问题描述】:

我有以下课程

public Building()
{
   public int Id{Get; Set;};
   public ICollection Bars{Get; Set;};
}

public Room()
{
   public int Id{Get; Set;};

   public int BuildingId{Get; Set;};
   public Building Building{Get; Set;}; 

   public string Name{Get; Set;); 
}

我希望建筑物内的每个房间都有一个唯一的名称。但是我不能让 Name 属性唯一,因为不同的建筑物可以有相同的房间名称

Room Table
Id    BuildingId    Name
1     1             Kitchen   
2     2             Kitchen    //Should be allowed as different building
3     1             Kitchen    //Should not be allowed

我能想到的唯一解决方案是在 BuildingId 和 Name 之间创建一个复合键。

modelBuilder.Entity<Room>().HasKey(r=> new {r.BuildingId, r.Name});

在 App 中获取房间会发生很多事情,将 Key 保持为一个简单的整数会简单得多。有没有办法让它成为一个独特的复合列而不使它成为键?

我相信我需要与 Index's 做一些事情,但我可以找到我所追求的工作示例。

【问题讨论】:

    标签: entity-framework-core


    【解决方案1】:

    在这种情况下,您不必使用复合键,而是可以将组合设为唯一。您必须使用HasIndexIsUnique 方法,如下所示。

    modelBuilder.Entity<Room>(b =>
                {
                    b.HasIndex(e => new { e.BuildingId, e.Name}).IsUnique();
                });
    

    【讨论】:

    • 我以为我需要某种索引,但我没有意识到我可以跨越多个列的索引。我今晚会试试看-谢谢
    • @Ben_jamin 当然,让我知道状态
    • 这已经解决了这个问题。正是需要的
    猜你喜欢
    • 2018-06-05
    • 2020-07-08
    • 2016-12-23
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多