I have a table with orders(around 8000 records),
The table takes a few seconds to load.
The reason for that is because one of the field shown on the page is being retrieved from another table
(returnProductName).
when removing this function the table loads fast.
When loading the records I'm using Skip and Take but when retrieving the product name i'm iterating all the Orders since if the user wants to search by product name it will show all results with this product.
The product table is not big (around 70 records)
I can't figure out why the function will make the page load so slow.
I know i can just add the product name column to the table and populate it when ever adding new orders,
but this doesn't sounds right,
Can anyone tell me the reason for this delay?
returnProductName Function :
public string returnProductName(int productId)
{
return (_unitOfWork.Product.GetAll().Where(q => q.Id == productId).Select(q =>
q.ProductName)).FirstOrDefault();
}
Function that loads the page data:
[HttpPost]
public ActionResult GetList()
{
//Server Side parameters
int start = Convert.ToInt32(Request.Form["start"].FirstOrDefault());
int length = Convert.ToInt32(Request.Form["length"].FirstOrDefault());
string searchValue = Request.Form["search[value]"].FirstOrDefault();
string sortColumnName = Request.Form["columns["+Request.Form["order[0][column]"]+"][name]"].FirstOrDefault();
string sortDirection = Request.Form["order[0][dir]"].FirstOrDefault();
List<Order> orderList = new List<Order>();
orderList = _unitOfWork.Order.GetAll().ToList();//Working Fast
int totalRows = orderList.Count;
foreach (Order order in orderList)
{
order.ProductName = returnProductName(order.ProductId);
}
if (!string.IsNullOrEmpty(searchValue))
{
orderList = orderList.Where(x => x.FullAddress.ToLower().Contains(searchValue.ToLower())
x.Id.ToString().Contains(searchValue.ToLower()) ||
x.OrderStatus.ToLower().Contains(searchValue.ToLower()) ||
x.ProductName.ToLower().Contains(searchValue.ToLower()) |||
x.Quantity.ToString().Contains(searchValue.ToLower()) ||
x.Cost.ToString().Contains(searchValue.ToLower()) ||
(!string.IsNullOrEmpty(x.TrackingNumber) && x.TrackingNumber.ToString().Contains(searchValue.ToLower()))
).ToList<Order>();
}
int totalRowsAfterFiltering = orderList.Count;
orderList = orderList.Skip(start).Take(length).ToList<Order>();
return Json(new { data = orderList, draw = Request.Form["draw"], recordsTotal = totalRows ,
recordsFiltered = totalRowsAfterFiltering});
}
I would perhaps consider updating the GetAll() method or creating another one which returns a dictionary.
In this case GetAllById() and then updating returnProductName which I would rename to GetProductName():
// Or whatever your type is
public Dictionary<int, List<Product>> GetAllById()
{
// your code..
return data
.GroupBy(x => x.Id)
.ToDictionary(x => x.Key, x => x.ToList());
}
public string GetProductName(int productId)
{
var products = _unitOfWork.Product.GetAllById();
return products[productId].FirstOrDefault(q => q.ProductName);
}
Related
how I can update a single value for an already existing row in the db by only having a parameters that I want to add it to this attribute
here is my code for a trivial way but didnt work
public bool BuyBook(int BookId, int UserId, int BookPrice){
using (var ctx = new OnlineBooksEntities())
{
User updatedCustomer = (from c in ctx.Users
where c.UserId == UserId
select c).FirstOrDefault();
updatedCustomer.Balance = BookPrice;
ctx.SaveChanges();
}
this.DeleteBook(BookId);
return true;
}
Add an sql query to the method solves the update aim
public bool BuyBook(int BookId, int UserId, int BookPrice)
{
try
{
using (var ctx = new OnlineBooksEntities())
{
User user = ctx.Users.Where(x => x.UserId == UserId).FirstOrDefault();
BookPrice = (int)user.Balance + BookPrice;
int noOfRowUpdated =
ctx.Database.ExecuteSqlCommand("Update Users set Balance = "+BookPrice+ " where UserId ="+UserId);
}
Updating basically means changing an existing row's value. Since you mentioned EF, you can do this by retrieving the object, changing its value, and saving it back. Thus you can do something like this:
using (var db = new MyContextDB())
{
var result = db.Books.SingleOrDefault(b => b.BookPrice == bookPrice);
if (result != null)
{
result.SomeValue = "Your new value here";
db.SaveChanges();
}
}
I am populating a list based on data returned from a stored procedure, this first occurs in the SpecificArea ActionResult:
public ActionResult SpecificArea(ModelCallDetails call, int id = 0 )
{
ReturnSpecificAreas(call, id);
return PartialView("SpecificArea", listCallDetails);
}
When the list is displayed each row is an actionlink, which will sends the data to the SpecificAreaWorker:
[HttpGet]
public ActionResult SpecificAreaWorker(ModelCallDetails call, int id)
{
TempData["StringOfIds"] = StringOfIds;
ReturnSpecificAreas(call, id);
if (ResponseMessage == "Successful")
{
return PartialView("SpecificArea", listCallDetails);
}
else
{
return RedirectToAction("ViewCall");
}
}
I am wanting to collect the id of each row that is clicked and store them in a list in the model so that I can create a string of id's. However, each time a row in the table is clicked it refreshes the model, and I no longer have a list of ids anymore.
public void ReturnSpecificAreas(ModelCallDetails call, int id)
{
SelectedAffectedServiceID = id;
call.AffectedServiceList.Add(SelectedAffectedServiceID);
foreach (int item in call.AffectedServiceList)
{
if (TempData["StringOfIds"] != null)
{
StringOfIds = TempData["StringOfIds"].ToString();
StringOfIds += string.Join(",", call.AffectedServiceList.ToArray());
}
else
{
StringOfIds += string.Join(",", call.AffectedServiceList.ToArray());
}
}
I have tried to mantain the data in tempdata, but can't manage to execute this -will the tempdata refresh each time the actionlink is clicked? Is there a better way to achieve this?
I believe you are using MVC5? If so, use
System.Web.HttpContext
This gets current request
to save....
System.Web.HttpContext.Current.Application["StringOfIds"] = StringOfIds; //Saves global
System.Web.HttpContext.Current.Session["StringOfIds"] = StringOfIds; //Saves Session
To retrieve...
StringOfIds = (string) System.Web.HttpContext.Current.Application ["StringOfIds"]; //Retrieves from global memory
StringOfIds = (string) System.Web.HttpContext.Current.Session ["StringOfIds"]; //retrieves from session memory
Good luck.
How to save mixed data in multiple tables if is checked checkbox:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "rID,AgentID,karta_br,Datum,patnikID,stanicaOD,stanicaDO,cena,povratna")] tbl_rezervacii tbl_rezervacii)
{
if (ModelState.IsValid)
{
if (tbl_rezervacii.povratna != true)
{
db.tbl_rezervacii.Add(tbl_rezervacii);
db.SaveChanges();
}
else
{
tbl_rezervacii rezervacii = new tbl_rezervacii()
{
???????????????????????
};
db.tbl_rezervacii.Add(rezervacii);
db.SaveChanges();
tbl_povratni povratni = new tbl_povratni()
{
???????????????????????
};
db.tbl_povratni.Add(povratni);
db.SaveChanges();
}
This is code in the controller, and I need to mix data from two forms, and save to two tables, I need something like this, and now my problem is just in else section of implementation.
I make application for Bus Ticket system, and i need this if is checked return way checkbox to add: rID (related with first table tbl_rezervacii), date of returning and relation of returning, include same agent id, price, etc. data which is saved in first tbl_rezervacii table.
MODIFIED CONTROLLER CODE:
public ActionResult Create([Bind(Include = "rID,AgentID,karta_br,Datum,patnikID,stanicaOD,stanicaDO,cena,povratna")] tbl_rezervacii tbl_rezervacii )
{
if (ModelState.IsValid)
{
if (tbl_rezervacii.povratna != true)
{
db.tbl_rezervacii.Add(tbl_rezervacii);
db.SaveChanges();
}
else
{
tbl_rezervacii rezervacii = new tbl_rezervacii()
{
AgentID = tbl_rezervacii.AgentID,
karta_br = tbl_rezervacii.karta_br,
Datum = tbl_rezervacii.Datum,
patnikID = tbl_rezervacii.patnikID,
stanicaOD = tbl_rezervacii.stanicaOD,
stanicaDO = tbl_rezervacii.stanicaDO,
cena = tbl_rezervacii.cena,
povratna = tbl_rezervacii.povratna
};
db.tbl_rezervacii.Add(rezervacii);
//db.SaveChanges();
var rows = db.SaveChanges();
tbl_povratni povratna = new tbl_povratni()
{
rezID = rezervacii.rID,
AgentID = rezervacii.AgentID,
karta_br = rezervacii.karta_br,
DatumP = **tbl_povratni.DatumP**,
patnikID = rezervacii.patnikID,
stanicaPOD = **tbl_povratni.stanicaPOD**,
stanicaPDO = **tbl_povratni.stanicaPDO**,
};
db.tbl_povratni.Add(povratna);
db.SaveChanges();
}
ViewBag.AgentID = new SelectList(db.tbl_agenti, "aID", "agent_ime", tbl_rezervacii.AgentID);
ViewBag.patnikID = new SelectList(db.tbl_patnici, "pID", "ime", tbl_rezervacii.patnikID);
ViewBag.stanicaOD = new SelectList(db.tbl_stanici, "sID", "stanica", tbl_rezervacii.stanicaOD);
ViewBag.stanicaDO = new SelectList(db.tbl_stanici, "sID", "stanica", tbl_rezervacii.stanicaDO);
ViewBag.stanicaPOD = new SelectList(db.tbl_stanici, "sID", "stanica", tbl_rezervacii.tbl_povratni.stanicaPOD);
ViewBag.stanicaPDO = new SelectList(db.tbl_stanici, "sID", "stanica", tbl_rezervacii.tbl_povratni.stanicaPDO);
return View(tbl_rezervacii);
}
return RedirectToAction("Index");
}
How to take data from secondary form and save together in second table?
So, if checkbox is checked, you want to save data into two tables and use primary key of first table (rID) in second table? If rID is auto increment, It will be updated by EF with the value assigned by the database.
tbl_rezervacii rezervacii = new tbl_rezervacii()
{
AgentID = tbl_rezervacii.AgendID,
karta_br = tbl_rezervacii.karta_br
// and so on...
};
db.tbl_rezervacii.Add(rezervacii);
var rows = db.SaveChanges(); // optional, rows will be > 0 if saved successfully.
tbl_povratni povratni = new tbl_povratni()
{
// if rID is auto increment
rID = rezervacii.rID,
// and so on...
};
db.tbl_povratni.Add(povratni);
db.SaveChanges();
I Create A News Site With MVC5 But I Have Problem .
in Model i Create A Repository Folder And in this i Create Rep_Setting for
Connect to Tbl_Setting in DataBase .
public class Rep_Setting
{
DataBase db = new DataBase();
public Tbl_Setting Tools()
{
try
{
var qGetSetting = (from a in db.Tbl_Setting
select a).FirstOrDefault();
return qGetSetting;
}
catch (Exception)
{
return null;
}
}
}
And i Create a Rep_News for Main Page .
DataBase db = new DataBase();
Rep_Setting RSetting = new Rep_Setting();
public List<Tbl_News> GetNews()
{
try
{
List<Tbl_News> qGetNews = (from a in db.Tbl_News
where a.Type.Equals("News")
select a).OrderByDescending(s => s.ID).Skip(0).Take(RSetting.Tools().CountNewsInPage).ToList();
return qGetNews;
}
catch (Exception ex)
{
return null;
}
}
But This Code Have Error to Me
OrderByDescending(s=>s.ID).Skip(0).Take(RSetting.Tools().CountNewsInPage).ToList();
Error :
Error 18 'System.Linq.IQueryable<NewsSite.Models.Domain.Tbl_News>' does
not contain a definition for 'Take' and the best extension method overload
'System.Linq.Queryable.Take<TSource>(System.Linq.IQueryable<TSource>, int)' has
some invalid arguments
E:\MyProject\NewsSite\NewsSite\Models\Repository\Rep_News.cs 50 52 NewsSite
How i Resolve it ?
Try it this way. The plan of debugging is to split your execution, this also makes for a more reusable method in many cases. And a good idea is to avoid using null and nullables if you can, if you use them "on purpose" the you must have a plan for them.
DataBase db = new DataBase();
Rep_Setting RSetting = new Rep_Setting();
public List<Tbl_News> GetNews()
{
int skip = 0;
Tbl_Setting tools = RSetting.Tools();
if(tools == null){ throw new Exception("Found no rows in the database table Tbl_Setting"); }
int? take = tools.CountNewsInPage;//Nullable
if(!take.HasValue)
{
// Do you want to do something if its null maybe set it to 0 and not null
take = 0;
}
string typeStr = "News";
List<Tbl_News> qGetNews = (from a in db.Tbl_News
where a.Type.Equals(typeStr)
select a).OrderByDescending(s => s.ID).Skip(skip).Take(take.Value);
return qGetNews.ToList();
}
if qGetNews is a empty list you now don't break everything after trying to iterate on it, like your return null would. instead if returning null for a lit return a new List<>() instead, gives you a more resilient result.
So I said reusable method, its more like a single action. So you work it around to this. Now you have something really reusable.
public List<Tbl_News> GetNews(string typeStr, int take, int skip = 0)
{
List<Tbl_News> qGetNews = (from a in db.Tbl_News
where a.Type.Equals(typeStr)
select a).OrderByDescending(s => s.ID).Skip(skip).Take(take);
return qGetNews.ToList();
}
Infact you shjould always try to avoid returning null if you can.
public class Rep_Setting
{
DataBase db = new DataBase();
public Tbl_Setting Tools()
{
var qGetSetting = (from a in db.Tbl_Setting
select a).FirstOrDefault();
if(qGetSetting == null){ throw new Exception("Found no rows in the database table Tbl_Setting"); }
return qGetSetting;
}
}
ISSUE:
I have an asp.net mvc 3 app. I'm using EF 4.1 and trying out jqGrid. I'm trying to get data for my jqGrid using the GridData method below. I get the following error on the group of data starting at 'var jsonData = new...'. Any ideas?
ERROR:
{"The array type 'System.String[]' cannot be initialized in a query result.
Consider using 'System.Collections.Generic.List`1[System.String]' instead."}
GridData Method:
public JsonResult GridData(string sidx, string sord, int page, int rows)
{
var result = from a in db.t_harvest_statistics_elk
where a.year == "2008" && a.unit_number == 1
orderby a.id
select a;
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = result.Count(); // context.Questions.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var questions = result.Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from question in questions
select new
{
i = question.id,
cell = new string[] { SqlFunctions.StringConvert((double)question.id), SqlFunctions.StringConvert((double)question.total_rec_days), question.year }
}).ToArray()
};
return Json(jsonData);
}
HERE IS AN EXAMPLE THAT DOES WORK
public JsonResult DynamicGridData(string sidx, string sord, int page, int rows)
{
var context = new HaackOverflowDataContext();
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
int totalRecords = context.Questions.Count();
int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
var questions = context.Questions.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize).Take(pageSize);
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = (
from question in questions
select new
{
i = question.Id,
cell = new string[] { question.Id.ToString(), question.Votes.ToString(), question.Title }
}).ToArray()
};
return Json(jsonData);
}
The easiest way to fix the code will be to use something like the following
// to be able to use ToString() below which is NOT exist in the LINQ to Entity
// so we should get the data from the database and save the result locally before
// the next step. One can use .ToList() or to .AsEnumerable(), but one should
// choose only the fields of questions which we will need later
var queryDetails = (from item in questions
select new { item.id, item.total_rec_days, item.year }).ToList();
var jsonData = new {
total = totalPages,
page,
records = totalRecords,
rows = (
from question in queryDetails
select new
{
id = question.Id,
cell = new [] {
question.Id.ToString(),
question.total_rec_days.ToString(),
question.year.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Your current code contain some small problems like the usage of i = question.id instead of id = question.id.
I would recommend you to read the answer and download the demo from the answer which contains more recent and extended code.
var jsonData = new {
total = totalPages,
page,
records = totalRecords,
rows = (
from question in queryDetails
select new
{
id = question.Id,
cell = new IComparable[]{
question.Id.ToString(),
question.total_rec_days.ToString(),
question.year.ToString()
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Can you try modifying your code like :
rows = (
from question in questions.AsEnumerable() //AsEnumerable() is added to switch to LINQ to Entites to eager load the data.
select new
{
i = question.id,
cell = new string[] { SqlFunctions.StringConvert((double)question.id), SqlFunctions.StringConvert((double)question.total_rec_days), question.year }
}).ToArray()
Because the MSDN says that : "You cannot call this function directly. This function can only appear within a LINQ to Entities query." (Though the next line is little confusing in documentation)
You can't use custom functions inside direct queries to you database. Instead you can do something like this:
rows = questions.AsEnumerable()
//or select just that you want questions.Select(q=> new {g.Id, q.Votes,q.Title})
.Select(p=> new {
id = p.Id,
cell = new string[] { SqlFunctions.StringConvert((double)p.id), SqlFunctions.StringConvert((double)p.total_rec_days), p.year }
}).ToArray()
That should work.