Search code examples
c#asp.net-mvcentity-frameworkrepository-patternunit-of-work

How to insert / Delete record in repository pattern unit of work entity framework with combined primary key


I have a following table with only two column with combined primary key

Table Name : ProductByUser

Column 1 : ProductId (FK Ref. to Product Table)

Column 2 : UserId (FK Ref. to User Table)

Additional Information: In edmx also I am not able to view this table but it show direct relationship between Product & User Table.

I am not able to make out how to delete or Insert record into this table. As I am not directly able to create an object of this table. So kindly guide me on the same.


Solution

  • Finally got the way out , Hope this will help some one in future,

     void Insert(Product product, int intUserId)
      {
         _unitofWork.Db.Entry(product).Collection(i => i.Users).Load();
    
          UserRepository userRepo = new UserRepository(_unitofWork);
    
         product.Users.Add(userRepo.GetAll().FirstOrDefault(U => U.UserID == intUserId));
    
      }
    

    For deleting

     product.Users.Remove(userRepo.GetAll().FirstOrDefault(U => U.UserID == intUserId));