如何使用 .NET CORE 3.1 代码优先方法在两列的组合上添加唯一键约束?

How to add Unique Key Constraints on combination of two columns using .NET CORE 3.1 code first approch?

我正在使用 .NET CORE 3.1 版本和代码优先方法创建数据库。我的模型在 C# 中:

[Table("ProfileStore")]
public class ProfileStore : BaseEntity
{
    [ForeignKey("Profile")]
    public int ProfileId { get; set; }

    [ForeignKey("Store")]
    public int StoreId { get; set; }

    public virtual Stores.Store Store { get; set; }

    public virtual Profile Profile { get; set; }
}

这里的 Profile 和 Store 都是不同的 table,我在这个 table 中添加了这两个 table 的映射。现在我只想添加具有唯一组合的行。我该怎么做?

示例数据将是:

Id    ProfileId   StoreId
1        1           1
2        1           2
3        2           1
4        2           3
5        1           1    <------- This is should not insert when I will try to insert this.

使用Configuring Many To Many Relationships in Entity Framework Core。 首先,将每个实体的 ICollection 添加到另一个实体。


    public class Profile
    {
        // other property
        public ICollection<Store> Stores { get; set; }
    }  
    
    public class Store
    {
        // other property
        public ICollection<Profile> Profiles { get; set; }
    }

然后使用 FluentAPI 并按如下方式配置联结 table:


    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProfileStore>()
            .HasKey(ps => new { ps.ProfileId, bc.StoreId }).IsUnique();  
        modelBuilder.Entity<ProfileStore>()
            .HasOne(ps => ps.Profile)
            .WithMany(p => p.ProfileStore)
            .HasForeignKey(ps => ps.ProfileId);  
        modelBuilder.Entity<ProfileStore>()
            .HasOne(ps => ps.Store)
            .WithMany(s => s.ProfileStore)
            .HasForeignKey(ps => ps.StoreId);
    }

我试过下面的代码,它正在运行。在此代码更改后不要忘记添加迁移。

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ProfileStore>()
            .HasIndex(p => new { p.ProfileId, p.StoreId }).IsUnique();
    }