how to let this perform better?

Posts   
 
    
mafti
User
Posts: 38
Joined: 27-Oct-2004
# Posted on: 11-May-2006 10:35:30   

hi there,

i have currently roughly this code for a lot of users in ousercol it doesn't perform optimal wink


foreach(ent.UserEntity ouser in ousercol)
{
        switch (ouser.Role)
    {
        case "ClientService":
            CreateUserRole(ouser.Con_code,2);
                break;
        case "SystemAdmin":
            CreateUserRole(ouser.Con_code,26);
            CreateUserRole(ouser.Con_code,23);
            CreateUserRole(ouser.Con_code,16);
            break;
    }
}

private  void CreateUserRole(string concode,int roleid)
{
    try
    {
        ent.Sec_user_roleEntity osur= new ent.Sec_user_roleEntity();
        osur.Con_code=concode;
        osur.Role_ID=roleid;
        osur.Save();
    }
    catch(Exception ex)
    {
    }
}

how can i speed it up? i have tried to place it in a collection and try to save the collection. even with and without a transaction.

but my main problem with the collection is that when the Roles already exists it gives a PK-violation, and it won't(?) get on with the other records.

Walaa avatar
Walaa
Support Team
Posts: 14995
Joined: 21-Aug-2005
# Posted on: 11-May-2006 14:38:53   

The ideal approach is to use an entity collection or a Unit of Work to save all your entities at once.

But due to your special constraint, I'd suggest to first fetch all the Sec_user_roleEntity entities which has the same ouser.Con_code in an EntityCollection.

Then in the for loop you should add your entities to that collection, and save the collection after the for loop.

Now the EntityCollection has the property DoNotPerformAddIfPresent and it's default is true. Any already existing entity won't be added to the collection, and then only the new entities will be saved.