Check if the user exists Scenario:


Check if the user exists


If yes: update the details
Else: insert the user details





public bool AddUsers(IEnumerable&lt;UserDetail&gt; users)
    {
        using (var dbTransaction = System.Data.Entity.Database.DefaultConnectionFactory.CreateConnection("MyCon").BeginTransaction())
        {
            using (var entities = new MyDbEntities())
            {
                try
                {
                    foreach (var user in users)
                    {
                        // LINQ under observation
                        var userId = entities.tUsers.Where(u =&gt; u.UserName == user.UserName).Select(x =&gt; x.UserUID).FirstOrDefault();

                        if (userId &gt; 0)
                        {
                            //update

                        }
                        else
                        {
                             //insert
                        }

                    }
                    dbTransaction.Commit();
                    return true;
                }
                catch (Exception ex)
                {
                    dbTransaction.Rollback();
                    clsErrorHandling.WriteLog("ImportUsersHandler", "AddUsers", ex.Message.ToString());
                    return false;
                }
                finally
                {
                    dbTransaction.Dispose();
                }
            }
        }
    }


Please find the comment //LINQ under observation. 

Is there a better way to find the user?

Because if I do this way:-

 tblUser newUser = new tblUser() { Username = user.Username } ;


If the user exists then no issue then in case not then how do I check whether I need to do insert or update.
using (var dbTransaction = System.Data.Entity.Database.DefaultConnectionFactory.CreateConnection("MyCon").BeginTransaction())
// ...
finally
{
    dbTransaction.Dispose();
}



You're already using the transaction in a using statement which is shorthand for try/finally, where the finally block disposes the IDisposable. So you can remove your manual finally block completely, otherwise you're calling Dispose on the transaction twice.


  clsErrorHandling.WriteLog("ImportUsersHandler", "AddUsers", ex.Message.ToString());


ex.Message is already a string, no need to call ToString on it.