0

I have a POST method that takes two parameters one is a userID and the other one is a list of permissions that will be added to the user.

the thing is that for each POST method I will be inserting a lot of permissions like this.

{
  "sysUserId": 0,
  "permissionsToAdd": [
    1,3,5,6,8,500,80,650 ...
  ]
}

The internal Object model is composed like this:

int SysUserId 
byte SubscriptionId 
short PermissionId 
bool IsInactive 
int ModifiedBy 
List<Short> PermissionsToAdd 

What I have been doing is creating multiple objects each one with the required parameters just changing the permissionID(PermissionsToAdd is a list of shorts which I receive from the POST request).

public async Task <List<SysUserPermission>> SavePermissions(SysUserPermission obj)
    {

              var result =  db.Set<SysUserPermission>()

                for (int i = 0; i < obj.PermissionsToAdd.Count; i++)
                {
                    obj.PermissionId = obj.PermissionsToAdd[i];

                     await result.AddAsync(obj);
                }

    }

I can't seem to find a way to save all the objects at the same time.

I hope the question is clear enough, Thanks.

2 Answers 2

1

You can use AddRangeAsync(). The documentation is here.

So, the code should look like:

public async Task <List<SysUserPermission>> SavePermissions(SysUserPermission obj)
    {

              var result =  db.Set<SysUserPermission>()

                for (int i = 0; i < obj.PermissionsToAdd.Count; i++)
                {
                    obj.PermissionId = obj.PermissionsToAdd[i];
                }
              await result.AddRangeAsync(obj.PermissionsToAdd);
    }
Sign up to request clarification or add additional context in comments.

Comments

0

There is a product/package called Z Entity Framework that does this via a Bulk Insert function. The syntax is a single line in which you can add a list of records:

context.BulkInsert(listOfRecordsToAdd);

Using this is much faster than AddRangeAsync(...) when adding many records at once

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.