How to update a database with new information - c#

I am terrible with databases so please bear with me.
I have a program that gets some user information and adds it to a database table. I then later need to get more information for that table, and update it. To do so I have tried doing this:
public static void updateInfo(string ID, string email, bool pub)
{
try
{
//Get new data context
MyDataDataContext db = GetNewDataContext(); //Creates a new data context
//Table used to get user information
User user = db.Users.SingleOrDefault(x => x.UserId == long.Parse(ID));
//Checks to see if we have a match
if (user != null)
{
//Add values
user.Email = email;
user.Publish = publish;
}
//Prep to submit changes
db.Users.InsertOnSubmit(user);
//Submit changes
db.SubmitChanges();
}
catch (Exception ex)
{
//Log error
Log(ex.ToString());
}
}
But I get this error:
System.InvalidOperationException: Cannot add an entity that already exists.
I know this is because I already have an entry in the table, but I don't know how to edit the code to update, and not try to make a new one?
Why does this not work? Wouldn't submitting changes on a current item update that item and not make a new one?

The problem is
//Prep to submit changes
db.Users.InsertOnSubmit(user);
Because you got the user from the DB already, you don't need to re-associate it with the context.
Comment that out and you're good to go.
Just a style / usage comment as well. You should dispose your context:
public static void updateInfo(string ID, string email, bool pub)
{
try
{
using (MyDataDataContext db = GetNewDataContext())
{
User user = db.Users.SingleOrDefault(x => x.UserId == long.Parse(ID));
if (user != null)
{
user.Email = email;
user.Publish = publish;
}
db.SubmitChanges();
}
}
catch (Exception ex)
{
//Log error
Log(ex.ToString());
// TODO: Consider adding throw or telling the user of the error.
// throw;
}
}

Related

C# & ASP.NET MVC roles - rolling back deleted roles when passing through context and not commiting

This is the simplified partial pseudo code from the calling method:
using (var context = new ModelContext())
{
var transaction = context.Database.BeginTransaction();
try
{
// Delete stuff here
Users.DeleteAllByClient(context, clientToDelete.ClientId);
// And delete stuff here
transaction.Commit();
}
catch (Exception e)
{
transaction.Rollback();
return;
}
}
Take the example method, used to delete user details and their profile.
The ModelContext context is passed through to the method, which means that if the calling method does not commit transaction.Commit(); causing a rollback, this will not occur for the roles. They will have already been deleted.
Is it possible to add the Roles.RemoveUserFromRoles(item.User.UserName, roles); to the rollback?
I can't use TransactionScope (nested or not) as opposed to passing the context through.
public static void DeleteAllByClient(ModelContext context, int clientId)
{
// Users to delete
var models = context.UserDetails.Where(o => o.ClientId == clientId).ToList();
// list of user profiles
List<UserProfile> userProfileList = new List<UserProfile>();
foreach (var item in models)
{
var userProfile = context.UserProfiles.FirstOrDefault(o => o.UserId == item.UserId);
var roles = Roles.GetRolesForUser(userProfile.UserName);
// these need to roll back if commit doesn't happen
Roles.RemoveUserFromRoles(item.User.UserName, roles);
userProfileList.Add(userProfile);
}
if (models.Count > 0)
{
context.UserDetails.BulkDelete(models); // db tables specified for clarity
context.UserProfiles.BulkDelete(userProfileList);
}
}

Entity framework update related entities without concurrency conflict

I have two related entities: User and UserProfile. A user can have many profiles (settings). I want to be able to update them together, but I am currently getting concurrency error when i do so:
Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=472540 for information on understanding and handling optimistic concurrency exceptions.
This is my code to update:
public void UpdateUser(UserList user, int timeoutMins)
{
using (var ctx = GetCodingContext())
{
try
{
ctx.Entry(user).State = System.Data.Entity.EntityState.Modified;
CR_USER_PROFILE timeoutProfile = GetTimeoutUserProfile(user.UserGUID);
if (timeoutProfile != null && !timeoutProfile.PROFILE_VALUE.Equals(timeoutMins.ToString()))
{
timeoutProfile.PROFILE_VALUE = timeoutMins.ToString();
UpdateUserProfile(timeoutProfile,ctx);
}
else if(timeoutProfile == null && timeoutMins > 0)
{
var timeoutKey = FFCEnumerations.Profiles.Keys.Timeout.GetStringValue();
AddUserProfile(user, timeoutKey, timeoutMins.ToString(), ctx);
}
ctx.SaveChanges();
}
catch (Exception ex)
{
throw new Exception("Error occurred updating user " + ex);
}
}
}
public void UpdateUserProfile(CR_USER_PROFILE profile, CodingContext ctx)
{
try
{
ctx.Entry(profile).State = System.Data.Entity.EntityState.Modified;
}
catch (Exception)
{
throw new Exception("Error occurred updating User Profile");
}
}
public CR_USER_PROFILE GetTimeoutUserProfile(Guid userGuid)
{
using (var ctx = GetCodingContext())
{
var timeoutKey = FFCEnumerations.Profiles.Keys.Timeout.GetStringValue();
var profileList = ctx.CR_USER_PROFILE.Where(p => p.UserGUID == userGuid && p.PROFILE_TYPE_CD == timeoutKey);
return profileList.SingleOrDefault();
}
}
It works well when I add both entities, but not when updating. Any ideas?
I think this is where there's a lot of discussion on this problem - Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."
I figured out that I was using a different context for fetching the profile I wanted to update. This was causing the concurrency conflict because EF thought this entity was being changed somewhere else (another context). So, I created an overload for this method so I can pass the context as an argument and fetch the entity with the same context I was going to update it with.
public CR_USER_PROFILE GetTimeoutUserProfile(Guid userGuid, CodingContext ctx)
{
var timeoutKey = FFCEnumerations.Profiles.Keys.Timeout.GetStringValue();
var profileList = ctx.CR_USER_PROFILE.Where(p => p.UserGUID == userGuid && p.PROFILE_TYPE_CD == timeoutKey);
return profileList.SingleOrDefault();
}

Can't update with .Attach()

I'm trying to update my UserRoles table but it won't update. I'm trying to update two things : 1. the email 2. the user role. Because the update needs to happen in 2 tables I'm using two separate commands. When I run the update on the Email alone (Users) it works but if I update the role (AspUserRoles) it does nothing. When I run it both it doesn't work either because UserRoles.Attach(userRole) is preventing it from updating. I also get no errors.
I checked if ApplicationRole.Id and ApplicationUser.Id has a value and it does return the value I want.
Here's my UserController.cs :
public async Task<IActionResult> Edit(UserViewModel model, Guid id)
{
var alert = new Alert();
try
{
if(!ModelState.IsValid)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.INVALID;
throw new Exception();
}
var originalModel = ApplicationDbContext.Users.FirstOrDefault(u => u.Id == id);
var userRole = ApplicationDbContext.UserRoles.FirstOrDefault(i => i.UserId == id);
if(originalModel == null)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.NOTEXISTS;
throw new Exception();
}
originalModel.Email = model.ApplicationUser.Email;
userRole.RoleId = model.ApplicationRole.Id;
ApplicationDbContext.Users.Attach(originalModel);
ApplicationDbContext.UserRoles.Attach(userRole);
ApplicationDbContext.Entry(originalModel).State = EntityState.Modified;
if (await ApplicationDbContext.SaveChangesAsync() == 0)
{
alert.Message = alert.ExceptionMessage = ApplicationDbContextMessage.EDITNOK;
throw new Exception();
}
alert.Message = ApplicationDbContextMessage.EDITOK;
return RedirectToAction("Index");
}
catch(Exception ex)
{
alert.Type = AlertType.Error;
alert.ExceptionMessage = ex.Message;
model = await ViewModel(model.ApplicationUser);
ModelState.AddModelError(string.Empty, alert.ExceptionMessage);
}
return View(model);
}
The way you are modifying data in this code, you don't need to call Attach or Add on the Context to let it know about changes to entities, that will happen automatically.
From the moment you pull an entity out of a DbSet of the DbContext it is being tracked (attached) by that DbContext. When you call SaveChanges on the DbContext it will scan any entities that it is tracking, comparing current values to old values, to find changes. Those changes then get sent to the data base.
You should literally be able to remove 3 lines of code from what you originally posted and have it work.
...
originalModel.Email = model.ApplicationUser.Email;
userRole.RoleId = model.ApplicationRole.Id;
ApplicationDbContext.Users.Attach(originalModel); // <--- Delete this line
ApplicationDbContext.UserRoles.Attach(userRole); // <--- Delete this line
ApplicationDbContext.Entry(originalModel).State = EntityState.Modified; // <--- Delete this line
if (await ApplicationDbContext.SaveChangesAsync() == 0)
...
A little something else I noticed. It looks like you might be using one single DbContext instance for the entire application. That is usually considered an "Anti-Patern" in Entity Framework. You should create a new DbContext instance (with using) for every "logical" operation you perform. That instance should only be alive for the life of that operation.
In MVC, this is usually one DbContext instance per ActionMethod.

Entity Framework 5 Update works only once per object / row

I'm using Entity Framework 5 with MySQL Database and just wanted to update a row attribute "user_loginstatus" between 0 and 1. The first time when I log in via client it updates just fine for the first attempt, after trying to update again it doesn't do anything with no exception.
I log in like this:
public async void LoginExecute()
{
// Checking Connection before etc...
if (await _dataService.IsLoginDataValidTask(UserObj.Username, md5))
{
Trace.WriteLine("LoginCommand Execute: Eingeloggt");
UserObj = await _dataService.GetUserDataTask(UserObj.Username);
await _dataService.SetUserStatusTask(UserObj.Id, 1);
await _dataService.WriteLog(UserObj.Id, "login", "Programm", GetLocalAdress());
Messenger.Default.Send(UserObj);
Messenger.Default.Send(new NotificationMessage("GoToMenuPage"));
}
else
{
// Error Stuff...
}
}
SetUserStatus Method in DataService Class
public Task SetUserStatusTask(int id, int status)
{
return Task.Factory.StartNew(() =>
{
try
{
var user = _entities.users.Find(id);
user.user_loginstatus = status;
_entities.SaveChanges();
}
catch (Exception ex)
{
Trace.WriteLine("DataService SetUserStatusTask: " + ex.Message);
}
});
}
GetUserData Method in DataService Class
public Task<User> GetUserDataTask(string username)
{
return Task.Factory.StartNew(() =>
{
try
{
var user = from us in _entities.users
where us.user_name.Equals(username)
select new User
{
Id = us.user_id,
Username = us.user_name,
FirstName = us.user_firstname,
LastName = us.user_lastname,
Gender = us.user_gender,
Email = us.user_mail,
Group = us.user_usergroup,
Avatar = us.user_avatar,
LoginStatus = 1
};
return user.FirstOrDefault();
}
catch (Exception ex)
{
Trace.WriteLine("DataService GetUserDataTask: " + ex);
return null;
}
});
}
So "users" is my table from the database and "User" / "UserObj" my custom Object.
With the Messenger (from MVVM Light) I just set via MainViewModel the Views, reset the unused ViewModels (ViewModel = new VieModel(...); or ViewModel = null;) and pass the current / logged in User Object.
With the same strategy I just Logout like this
public ICommand LogoutCommand
{
get
{
return new RelayCommand(async () =>
{
await _dataService.SetUserStatusTask(CurrentUser.Id, 0);
if(CurrentUser.Id > 0 && IsLoggedIn)
await _dataService.WriteLog(CurrentUser.Id, "logout", "Programm", GetLocalAdress());
IsLoggedIn = false;
CurrentUser = new User();
Messenger.Default.Send(new NotificationMessage("GoToLoginPage"));
});
}
}
So I can log in with my running Client so often I want, but the "user_loginStatus" only sets the changes the first login time to 1 and back to 0, but when I log out then and login back with the same user, it wont change it anymore. When I login (still same running Client) with another user it sets again the first time the "user_loginstatus" to 1 and back to 0 and then only again when I restart my Client..
What could I do wrong?
This is just basically from my comment regarding the original question:
I had similiar problems several times. Usually it is based on the fact that the entity you modified can't be validated properly and your dbContext fails without a proper exception because it still holds on to false entity. If this is the case you could circumvent this problem by using scoped contexts and embedding your data access operations in a using statement.
Alternatively you could try to explicitly tell EF that the entity has changes e.g.:
_entities.Entry(user).State = EntityState.Modified;
Regarding your other question:
In theory you shouldn't have to tell EF explicitly that the entity's values have changed. Change tracking should do that automatically. The only exception i could think of, is when you try to modify an entity that is explicitly not tracked anymore. When you call _entities.Find(id) it will look in the context if it finds the object with the matching primary key value and load it. Since you already modified this object before, the context will simply get the old object you already modified to set the login status the first time.
This "old" object is probably not tracked anymore and you have to tell EF explicitly that it has changed, by changing it's state from attached to modified.
in LoginExecute() you have UserObj, but in LogoutCommand() you have CurrentUser. Is it OK?

.Net mvc EF codefirst how to hanle concurrent update requests to database

I've got a table in database:
USERID MONEY
______________
1 500
The money value could be changed only by logged in user that owns account. I've got a function like:
bool buy(int moneyToSpend)
{
var moneyRow = db.UserMoney.Find(loggedinUserID);
if(moneyRow.MONEY < moneyToSpend)
return false;
//code for placing order
moneyRow.MONEY -= moneyToSpend;
return true;
}
I know that mvc sessions are always synchronous, so there will never be 2 symulateous calls to this function in one user session. But what if user logs in to the site 2 times from different browsers? Will it be still single threaded session or I can get 2 concurrent requests to this function?
And if there will be concurrency then how should I handle it with EF? Normally in ADO I would use MSSQL's "BEGIN WORK" for this type of situation, but I have no idea on how to make it with EF.
Thank you for your time!
I would suggest you to use RowVersion to handle concurrent requests.
Good reference here: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application
// in UserMoney.cs
[Timestamp]
public byte[] RowVersion { get; set; }
// in model builder
modelBuilder.Entity<UserMoney>().Property(p => p.RowVersion).IsConcurrencyToken();
// The update logic
public bool Buy(int moneyToSpend, byte[] rowVersion)
{
try
{
var moneyRow = db.UserMoney.Find(loggedinUserID);
if(moneyRow.MONEY < moneyToSpend)
{
return false;
}
//code for placing order
moneyRow.MONEY -= moneyToSpend;
return true;
}
catch (DbUpdateConcurrencyException ex)
{
var entry = ex.Entries.Single();
var submittedUserMoney = (UserMoney) entry.Entity;
var databaseValue = entry.GetDatabaseValues();
if (databaseValue == null)
{
// this entry is no longer existed in db
}
else
{
// this entry is existed and have newer version in db
var userMoneyInDb = (UserMoney) databaseValue.ToObject();
}
}
catch (RetryLimitExceededException)
{
// probably put some logs here
}
}
I do not think it would be a major problem for you since the idea is that MSSQL as far as i know will not allow asyncroneus data commits to the same user from the same thread it has to finish one process before moving to the next one but you can try something like this
using (var db = new YourContext())
{
var moneyRow = db.UserMoney.Find(loggedinUserID);
moneyRow.MONEY -= moneyToSpend;
bool saveFailed;
do
{
saveFailed = false;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
saveFailed = true;
// Update original values from the database
var entry = ex.Entries.Single();
entry.OriginalValues.SetValues(entry.GetDatabaseValues());
}
} while (saveFailed);
}
More can be found here Optimistic Concurrency Patterns

Categories

Resources