0

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.

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I had tried this but not working. Need to add migration after adding these properties?
it's better to rollback previous migration, and try it again with this config, maybe work
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.