Scenario:
- Check if the user exists
- If yes: update the details
- Else: insert the user details
public bool AddUsers(IEnumerable<UserDetail> 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 => u.UserName == user.UserName).Select(x => x.UserUID).FirstOrDefault();
if (userId > 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.