How to tackle this error Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException? - asp.net

Message:
Database operation expected to affect 1 row(s) but actually affected 0 row(s).
I am trying to update user info in the database but I get this error.
public IActionResult OnPost()
{
if (!string.IsNullOrEmpty(user.Password))
{
PasswordHasher<User> Hasher = new PasswordHasher<User>();
user.Password = Hasher.HashPassword(user, user.Password);
}
else
{
//user.Password = _mycontext.Users
// .SingleOrDefault(a => a.Id == user.Id).Password;
}
_mycontext.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
_mycontext.SaveChanges();
return Page();
}

Related

the value cookies deleted while redirect ASP.NET

the cookies deleted after redirecting but sessions are still active. do you know whats the problem. I searched a lot but did not find my answer.
this is my codes:
[ValidateAntiForgeryToken]
public ActionResult SetLogIn(string doctorName, string passwords)
{
var status = 0;
var logInDoctor = context.doctors_tbl.Where(x => x.name == doctorName && x.password == passwords).SingleOrDefault();
if (logInDoctor != null)
{
Response.Cookies["UserID"].Value = logInDoctor.pkID.ToString();
Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(500);
status = 1;
}
else
{
status = 0;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
$.post('/Home/SetLogIn', { doctorName: name, passwords: pass, __requestverificationtoken: token })
.done(
function (req) {
switch (req) {
case 1:
swal('ok')
window.location = '/Home/recept/'
break
case 2:
swal('bad')
}
}
)
if (Response.Cookies["UserID"] == null || Response.Cookies["UserID"].Value == null)
{
Response.Redirect("~/Home/login");
}
I delete cookies and rerun the project but problem not fixed

Problem with adding new object to data base

Hi i have an error when i trying add object to database. Error message is:
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.
My adding methods:
public void AddProduct(string category, FormCollection formCollection, HttpPostedFileBase image) //Dodaje nowy produkt do bazy.
{
var product = GetNewProduct(category);
var EfContext = GetEfContext(category);
foreach(var property in product.GetType().GetProperties())
{
if(property.Name != "ImageData" && property.Name != "ImageMimeType")
{
var NewValue = Convert.ChangeType(formCollection[property.Name], property.PropertyType);
property.SetValue(product, NewValue);
}
else
{
if (property.Name == "ImageData")
{
property.SetValue(product, new byte[image.ContentLength]);
}
if(property.Name == "ImageMimeType")
{
property.SetValue(product, image.ContentType);
}
if(product.GetType().GetProperty("ImageData").GetValue(product) != null && product.GetType().GetProperty("ImageMimeType").GetValue(product) != null)
{
image.InputStream.Read((byte[])product.GetType().GetProperty("ImageData").GetValue(product), 0, image.ContentLength);
}
}
}
EfContext.GetType().GetMethod("AddProduct").Invoke(EfContext, new object[] { product });
}
And
public void AddProduct(GPU product)
{
product.Product_ID = productContext.items.Count() != 0 ? productContext.items.OrderByDescending(x => x.ProductID).Select(x => x.ProductID).FirstOrDefault() + 1 : 1;
context.GPUs.Add(product);
context.SaveChanges();
}

Cannot post update to database. not all code paths return a value

[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
return View(user);
}
}
I keep on getting an error while saving data to the database.
UpdateDetail worked while retrieving message, but i keep getting error when saving.
Your issue is if your ModelState.IsValid == false, then you are not returning anything. I put a comment in code below where it is.
Depending on what your logic needs to do, would determine what needs to be returned if IsValid == false
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
// this is your issue, this needs to be outisde the if statement, or you have to do an else and return null (or whatever you need to based off your logic)
return View(user);
}
}
Keep return statement outside of If statement. this would fix your error.If model is valid model updated with user details from database will be pushed to View. other wise same user model will be pushed to the view.
[HttpPost]
public ActionResult UpdateDetail(User user)
{
bool Status = false;
string message = "";
// Model Validation
if (ModelState.IsValid)
{
using (UsersDatabaseEntities ude = new UsersDatabaseEntities())
{
var v = ude.Users.Where(a => a.Email == User.Identity.Name).FirstOrDefault();
user = v;
ude.Entry(User).State = EntityState.Modified;
ude.SaveChanges();
}
}
return View(user);
}

Update Using Entity Framework is not reflecting my DB table

I'm new to Entity Framework, and wrote a function to update a particular column TStatus.
Here is what I'm trying to execute:
public ActionResult UpdateTStatus(int ICCID)
{
using (var db = new MyDBContext())
{
var result = db.INTERVIEW_AGENT_CALL_CENTERS.Where(g => g.Id == ICCID).FirstOrDefault();
if (result != null)
{
result.TStatus= 10;
db.Entry(result).State = EntityState.Modified;
db.SaveChanges();
return Content("Result = "+result.TStatus);
}
else
{
return Content("An Error");
}
}
return View();
}
Whenever I'm executing the method and run a direct query on SQL Server, I'm getting the old value of TStatus.

The procedure does not work properly Entity Framework ASP.NET MVC 5 C#5

I have been facing this problem with assigning users to a proper role. The code looks just fine, but in reality half of the users gets a proper role, the other half stays without a role at all. Here is the method which does it:
public IdentityResult RefreshUserGroupRoles(long? userId)
{
if (userId == null) throw new ArgumentNullException(nameof(userId));
var user = _userManager.FindById(userId.Value);
if(user == null)
{
throw new ArgumentNullException(nameof(userId));
}
// Remove user from previous roles:
var oldUserRoles = _userManager.GetRoles(userId.Value);
if (oldUserRoles.Count > 0)
{
_userManager.RemoveFromRoles(userId.Value, oldUserRoles.ToArray());
}
// Find the roles this user is entitled to from group membership:
var newGroupRoles = this.GetUserGroupRoles(userId.Value);
// Get the damn role names:
var allRoles = _roleManager.Roles.ToList();
var addTheseRoles = allRoles.Where(r => newGroupRoles.Any(gr => gr.AppRoleId == r.Id));
var roleNames = addTheseRoles.Select(n => n.Name).ToArray();
//_db.Database.CurrentTransaction.Commit();
// Add the user to the proper roles
var transaction = _db.Database.BeginTransaction();
IdentityResult result;
try
{
result = _userManager.AddToRoles(userId.Value, roleNames);
transaction.Commit();
_db.DbContextTransactionAu.Commit(); //This is for Audit
}
catch (Exception)
{
transaction.Rollback();
throw;
}
_db.DbContextTransactionAuDispose?.Dispose();
return result;
}
public IEnumerable<AppGroupRole> GetUserGroupRoles(long userId)
{
var userGroups = this.GetUserGroups(userId).ToList();
if (userGroups.Count == 0) return new Collection<AppGroupRole>().AsEnumerable();
var userGroupRoles = new List<AppGroupRole>();
foreach(var group in userGroups)
{
userGroupRoles.AddRange(group.AppRoles.ToArray());
}
return userGroupRoles;
}
Any idea what could be wrong?

Resources