Field in Database Not updating while using SubmitChanges() - c#

I'm trying to update 2 field in my database using Database Context
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeDefaultUserLockingSetting(int PasswordAttempts, int DefaultLockingTime)
{
var defaultAccountSettings = new DefaultAccountSettingsDataContext();
var defaultLockoutTimeSpam = defaultAccountSettings.DefaultAccountSettings.Where(u=>u.id==1).Select(u=>u.DefaultAccountLockoutTimeSpan).First();
var maxFailedAccessAttemptsBeforeLockout = defaultAccountSettings.DefaultAccountSettings.Where(u => u.id == 1).Select(u=>u.MaxFailedAccessAttemptsBeforeLockout).First();
//foreach (int item in defaultLockoutTimeSpam)
{
defaultLockoutTimeSpam = DefaultLockingTime;
}
maxFailedAccessAttemptsBeforeLockout = DefaultLockingTime;
defaultAccountSettings.SubmitChanges();
return View("Index", loadAdministrationViewModel());
}
What I am doing wrong?

You need to try this code.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ChangeDefaultUserLockingSetting(int PasswordAttempts, int DefaultLockingTime)
{
var defaultAccountSettings = new DefaultAccountSettingsDataContext();
var defaultLockoutTimeSpam = defaultAccountSettings.DefaultAccountSettings.Where(u => u.id == 1).FirstOrDefault();
var maxFailedAccessAttemptsBeforeLockout = defaultAccountSettings.DefaultAccountSettings.Where(u => u.id == 1).FirstOrDefault();
//foreach (int item in defaultLockoutTimeSpam)
{
defaultLockoutTimeSpam.DefaultAccountLockoutTimeSpan = DefaultLockingTime;
}
maxFailedAccessAttemptsBeforeLockout.MaxFailedAccessAttemptsBeforeLockout = DefaultLockingTime;
defaultAccountSettings.SubmitChanges();
return View("Index", loadAdministrationViewModel());
}

I was modifying the values but not the Object
This is the proper way to do it :
public ActionResult ChangeDefaultUserLockingSetting(int PasswordAttempts, int DefaultLockingTime)
{
var defaultAccountSettings = new DefaultAccountSettingsDataContext();
var accountSettings = defaultAccountSettings.DefaultAccountSettings.First(u => u.id == 1);
//The object should be modified and not his local value
accountSettings.DefaultAccountLockoutTimeSpan = DefaultLockingTime;
accountSettings.MaxFailedAccessAttemptsBeforeLockout = PasswordAttempts;
defaultAccountSettings.SubmitChanges();
return View("Index", loadAdministrationViewModel());
}

Related

using group by for getting some statistic data from one table with bulk records and puting the results into the second table

As I explained in title I have 2 tables :
1 - "Leaves" with 21000 rec of leaves for about 50 peoples during 20 years
2- "StatisticLeave" which is empty
now i want to use group by for getting some statistic data from table 1 and after doing some calculation (like sum & ...) putting the results into the second table.
I wrote below code :
public ActionResult UserStatistic()
{
var ST = new List<StatisticLeave>();
var resuls = db.Leaves.GroupBy(p => p.Pcode);
foreach (var Pcode in resuls)
{
var statistic = new StatisticLeave();
foreach (var item in Pcode)
{
var used = UsedLeaves(item.Pcode);
var estelaji = db.Leaves.Where(p => p.DLT == Leave.DLType.Estelaji).Sum(p => p.LeaveDays);
var bh = db.Leaves.Where(p => p.DLT == Leave.DLType.Bihoghoogh).Sum(p => p.LeaveDays);
statistic.Yearlyhours = ViewBag.mins/60;
statistic.YearlyDays = ViewBag.days;
statistic.YearEstelaji = estelaji;
statistic.YearBihoghoogh = bh;
statistic.Pcode = item.Pcode;
statistic.Year = item.HijriYear;
statistic.UsedYearLaeve = (used / 60) / 8;
ST.Add(statistic);
}
db.StatisticLeave.AddRange(ST);
}
db.SaveChanges();
return View();
}
when I trace the code i get the following caution:
"System.InvalidOperationException
HResult=0x80131509
Message=Unable to translate the given 'GroupBy' pattern. Call 'AsEnumerable' before 'GroupBy' to evaluate it client-side."
would you please tell me where is the problem or how can i fix it.
I changed my code as below and the problem Solved
public ActionResult UserStatistic(Int32? PCode)
{
var ST = new List<StatisticLeave>();
var results = db.Leaves.Where(p => p.Pcode == PCode).ToLookup(p => p.HijriYear);
foreach (var HijriYear in results)
{
var statistic = new StatisticLeave();
foreach (var item in HijriYear)
{
var used = UsedLeaves(item.Pcode, item.HijriYear);
var estelaji = db.Leaves.Where(x => x.Pcode == item.Pcode).Where(p => p.DLT == Leave.DLType.Estelaji).Where(p => p.HijriYear == item.HijriYear).Sum(p => p.LeaveDays);
var bh = db.Leaves.Where(x => x.Pcode == item.Pcode).Where(p => p.DLT == Leave.DLType.Bihoghoogh).Where(p => p.HijriYear == item.HijriYear).Sum(p => p.LeaveDays);
statistic.Yearlyhours = ViewBag.mins / 60;
statistic.YearlyDays = ViewBag.days;
statistic.YearEstelaji = estelaji;
statistic.YearBihoghoogh = bh;
statistic.Pcode = item.Pcode;
statistic.Year = item.HijriYear;
statistic.UsedYearLaeve = (used / 60) / 8;
ST.Add(statistic);
}
db.StatisticLeave.AddRange(ST);
}
db.SaveChanges();
return View();
}

Combination of two conditions in .cs code

Desc
I have a problem with the "where" instruction from the .cs code, I don't know how to use "and" there?
I tried
Code dont run, "and" dont exist
[HttpGet]
public ActionResult GetNumberDays(string mieciacValue, int rokValue)
{
var liczbaDni = _ecpContext.Miesiace.Where(x => x.Rok == rokValue and x => x.Miesiac == miesiacValue).Select(i => new
{
ObecnaIloscDni = i.IloscDni
});
return null;
}
Replace the and by &&. See the documentation for more Details.
eg:
[HttpGet]
public ActionResult GetNumberDays(string mieciacValue, int rokValue)
{
var liczbaDni = _ecpContext.Miesiace.Where(x => x.Rok == rokValue && x.Miesiac == miesiacValue).Select(i => new
{
ObecnaIloscDni = i.IloscDni
});
return null;
}

Sorting Data using LINQ.Dynamic

I want to populate a table using JSON data. This works perfectly.
However the issue occurs when I want to view the data. I keep on running into
'No property or field 'RegistrationIDasc' exists in type 'UserModel'.
My UserModel contains the string RegistrationID.I don't understand the addtional "asc".
This is the controller
public ActionResult LoadRolesData()
{
try
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var rolesData = _IAssignRoles.ShowallRoles(sortColumn, sortColumnDir, searchValue);
recordsTotal = rolesData.Count();
return Json(new { draw, recordsFiltered = recordsTotal, recordsTotal });
}
catch (Exception)
{
throw; //exception thrown here
}
}
Below is the class model
public IQueryable<UserModel> ShowallRoles(string sortColumn, string sortColumnDir, string Search)
{
var result = (from AssignedRoles in db.AssignedRoles
join registration in db.Registration on AssignedRoles.RegistrationID equals registration.RegistrationID
join AssignedRolesAdmin in db.Registration on AssignedRoles.AssignToAdmin equals AssignedRolesAdmin.RegistrationID
select new UserModel
{
Name = registration.Name,
AssignToAdmin = string.IsNullOrEmpty(AssignedRolesAdmin.Name) ? "*Not Assigned*" : AssignedRolesAdmin.Name.ToUpper(),
RegistrationID = registration.RegistrationID
});
if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDir))) //first exception thrown
{
result = result.Where(sortColumn + "" + sortColumnDir);
}
if (!string.IsNullOrEmpty(Search))
{
result = result.Where(m => m.Name == Search);
}
return result;
}
Pseudo code
public IQueryable<UserModel> ShowallRoles(string sortColumn, string sortColumnDir, string Search)
{
var result = (from AssignedRoles in db.AssignedRoles
join registration in db.Registration on AssignedRoles.RegistrationID equals registration.RegistrationID
join AssignedRolesAdmin in db.Registration on AssignedRoles.AssignToAdmin equals AssignedRolesAdmin.RegistrationID
select new UserModel
{
Name = registration.Name,
AssignToAdmin = string.IsNullOrEmpty(AssignedRolesAdmin.Name) ? "*Not Assigned*" : AssignedRolesAdmin.Name.ToUpper(),
RegistrationID = registration.RegistrationID
});
if (!string.IsNullOrEmpty(Search))
{
result = result.Where(m => m.Name == Search);
}
if (!string.IsNullOrEmpty(sortColumn))
{
if (!string.IsNullOrEmpty(sortColumnDir))
{
if(sortColumnDir == "asc")
result = result.OrderBy(sortColumn);
else
result = result.OrderByDescending(sortColumn);
}
}
return result;
}

Add to int filed each time an action called?

I want to increase 1 unit of my int field named BookViews by per action run.
My Action :
[HttpGet]
public IActionResult BookDetails(int id)
{
MultiModels model = new MultiModels();
model.UserListed = (from u in _userManager.Users orderby u.Id descending select u).Take(10).ToList();
using (var db = _iServiceProvider.GetRequiredService<ApplicationDbContext>())
{
var result = from b in db.books where (b.BookId == id) select b;
if (result.Count() != 0)
{
///error occure here
db.books.Update((from b in db.books where b.BookId == id select b.BookViews) + 1));
db.SaveChanges();
}
}
return View(model);
}
But my code get error. How can i increase BookViews field 1 unit per run and update it in database?
Try retrieving the book that you want, increment your BookViews and then call SaveChanges():
var currentBook = result.ToList().FirstOrDefault();
if(currentBook != null){
currentBook.BookViews++;
db.Books.Attach(currentBook );
//Changing the State
db.Entry(currentBook ).State = EntityState.Modified;
db.SaveChanges();
}
Edit
Please try to be more especific, we are reallt trying to help you, but I cant't guess the error's that you are getting or what the varibles in your code do, if you don't explain...

Entity Random Select from DB C# MVC

Try to find the solution but i cant.
So problem is next one. I have the EDM model of database. I have a class with functions to get data from DB.
Like this:
public IQueryable<photos> FindUserPhotos(string userlogin)
{
return from m in db.photos
where m.userlogin == userlogin
select m;
}
How to get the Random 10 lines from DB?
I always use this method for get custom entity OrderBy(x => Guid.NewGuid())
public photos Find10RandomUserPhotos(string userlogin)
{
return db.photos.Where(x => x.userlogin == userlogin).OrderBy(x => Guid.NewGuid()).Take(10).ToList();
}
Following Random row from Linq to Sql
public photos FindRandomUserPhoto(string userlogin)
{
var qry = FindUserPhotos(userlogin);
int count = qry.Count();
int index = new Random().Next(count);
return qry.Skip(index).FirstOrDefault();
}
public Array<photos> Find10RandomUserPhotos(string userlogin)
{
var result = New Array<photos>;
for (i = 0; i < 10; i++) {
result.add(FindRandomUserPhoto(userlogin));
}
return result
}

Categories