Srusti Thakkar
Srusti Thakkar

Reputation: 1901

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

I am using .NET CORE 3.1 version and code first approach for Database creation. My model is in 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; }
}

Here Profile and Store both are different table and I am adding mapping of this two table in this table. Now I want to add row with unique combination only. How can I do that?

Sample Data Will be :

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.

Upvotes: 0

Views: 1110

Answers (2)

Sina Riani
Sina Riani

Reputation: 345

Use Configuring Many To Many Relationships in Entity Framework Core. First, add ICollection of each entity to the other one.


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

then use FluentAPI and configure the junction table as follow:


    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);
    }

Upvotes: 1

Srusti Thakkar
Srusti Thakkar

Reputation: 1901

I had tried below code and it's working. Don't forgot to add migration after this code change.

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

Upvotes: 0

Related Questions