MY Asp.Net MVC page takes 12 secs. to load - c#

I have an MVC Controller like this
public ActionResult Index(int vendor=-1, int product = -1, string error="", string mode="Shortfall")
{
if (Session["UserId"] == null)
return RedirectToAction("Index", "Login");
var products = DbContext.GetAllProducts();
List<SurplusViewModel> surplusList = new List<SurplusViewModel>();
Dictionary<int, string> searchVendor = new Dictionary<int, string>();
Dictionary<int, string> searchProds = new Dictionary<int, string>();
if (products.Count() > 0)
{
foreach (var prod in products)
{
SurplusViewModel s = new SurplusViewModel(prod);
surplusList.Add(s);
foreach (var v in s.Vendors)
{
if (!searchVendor.ContainsKey(v.CorpId))
{
searchVendor.Add(v.CorpId, v.CorpName);
}
}
if(!searchProds.ContainsKey(s.ProductId))
searchProds.Add(s.ProductId, s.ProductVM.ProductCode + " / " + s.ProductVM.ProductPartNo);
}
}
ViewData["vendorList"] = searchVendor;
ViewData["productList"] = searchProds;
ViewData["selectVendor"] = vendor;
ViewData["selectProd"] = product;
ViewData["mode"] = mode;
ViewBag.Message = "";
ViewBag.Error = "";
IEnumerable<SurplusViewModel> finalList = surplusList.OrderBy(o => o.Difference).ToList();
if (vendor > 0)
{
Corporation searchcorp = DbContext.GetCorporation(vendor);
finalList = finalList.Where(x => x.VendorNames.IndexOf(searchcorp.CorpName) >= 0);
}
if (product > 0)
{
finalList = finalList.Where(x => x.ProductId == product);
}
if (vendor < 0 && product < 0)
{
if (mode.Equals("Shortfall"))
finalList = finalList.Where(f => f.VendorQuantity - (f.CMQuantity + f.OEMQuantity) < 0);
else if (mode.Equals("Surplus"))
finalList = finalList.Where(f => f.VendorQuantity - (f.CMQuantity + f.OEMQuantity) > 0);
}
return View(finalList);
//return View();
}
This takes about 20 seconds to load on localhost. What can I do to improve my app's loading time. If it takes 20 secs on localhost I assume it will be very slow on the internet. Any suggestions?
EDIT: Code for SurplusViewModel
public SurplusViewModel(Product product)
{
int productId = product.ProductId;
ProductId = productId;
ProductVM = new ProductViewModel(product);
var saleDetsCM = from s in DbContext.GetSalesOrderDetailsFromCM()
where s.ProductId == productId && s.SaleStatus.Equals("Open") && (s.OrderType.ToLower().Equals("prototype") || s.OrderType.ToLower().Equals("production"))
orderby s.SalDetId descending
select s;
var saleDetsOEM = from s in DbContext.GetSalesOrderDetailsFromOEMs()
where s.ProductId == productId && s.SaleStatus.Equals("Open") && (s.OrderType.ToLower().Equals("prototype") || s.OrderType.ToLower().Equals("production"))
orderby s.SalDetId descending
select s;
var shipQty = from s in DbContext.GetAllSalesDets()
where s.ProductId == productId && !s.SaleStatus.Equals("Open") && (s.OrderType.ToLower().Equals("prototype") || s.OrderType.ToLower().Equals("production"))
orderby s.SalDetId descending
select s;
CustomerOrdersFromCMs = saleDetsCM.ToList();
CustomerOrdersFromOEMs = saleDetsOEM.ToList();
VendorOrders = (from p in DbContext.GetPurchaseDetsForProduct(productId)
where p.OrderType != null && (p.OrderType.ToLower().Equals("prototype") || p.OrderType.ToLower().Equals("production"))
select p).ToList();
var poIds = from v in VendorOrders
select v.PodPOId;
BatchPurchaseDetails = DbContext.GetBatchPurchaseForProduct(productId).ToList();
VendorOrderCount = 0;
VendorQuantity = 0;
var purchaseOrds = (from po in DbContext.GetPurchaseOrdersForProduct(productId)
where poIds.Contains(po.POId)
select po).ToList();
List<int> vendIds = new List<int>();
foreach (var po in purchaseOrds)
{
vendIds.Add(po.VendorId.Value);
}
var vendors = from v in DbContext.GetAllCorps()
where vendIds.Contains(v.CorpId)
select v;
foreach (var podet in VendorOrders)
{
double totalbatchqty = 0;
var purdetBatch = DbContext.GetBatchDetailsForPurchaseDet(podet.PodId);
VendorQuantity += podet.Quantity;
foreach (var b in purdetBatch)
{
totalbatchqty += b.Quantity;
VendorQuantity -= b.Quantity;
}
if (totalbatchqty >= podet.Quantity)
{
}
else
{
VendorOrderCount++;
}
}
Vendors = vendors.ToList();
VendorNames = "";
foreach (var vnd in Vendors)
{
VendorNames += vnd.CorpName + ",";
}
if (VendorNames.Length > 0)
{
VendorNames = VendorNames.Substring(0, VendorNames.Length - 1);
}
OEMQuantity = 0;
foreach (var item in CustomerOrdersFromOEMs)
{
OEMQuantity += item.Quantity;
}
CMQuantity = 0;
foreach (var item in CustomerOrdersFromCMs)
{
CMQuantity += item.Quantity;
}
ShipQuantity = 0;
foreach (var item in shipQty)
{
ShipQuantity += item.Quantity;
}
Difference = VendorQuantity - (CMQuantity + OEMQuantity);
//TotalInsideSalesOrder = VendorOrders.Count();
}

You're doing a ton of things wrong, or at least very poorly. First, you're returning all records from various queries, the processing them in memory. This is fine if there are only a few records, but you mention that there are 50 products. How many Vendors? How many Corporations?
You're doing several database queries, and it sounds like you're doing even more queries in sub-objects you instantiate. All of those queries take time. That's why you want to minimize queries by writing more inclusive single queries, and performing as much work on the sql server as possible in a single (or as few as possible) queries.
Areas you can optimize... Don't do Count() > 0, instead use .Any(). .Any returns true after the first record it finds, rather than having to count everything and then compare that number to 0.
Another area, you're doing a foreach inside a foreach. This creates n * m loops. ie, if there's 2 products and 2 vendors, that's 4 loops, but if it's 3 of each, it's 9 loops, if it's 4 of each it's 16 loops. if it's 50 of each 2500 loops. And each one of those loops executes your SurplusViewModel constructor, which if it's a lot of code means it's going to be sloooooooow.
I see from your update, that SurplusViewModel executes at least 7 queries, maybe more.. it's hard to tell. so that's 2500 * 7 or 17,500 Queries (assuming 50 products, and 50 vendors). Are you beginning to see why it's so slow? Now, Imagine you had 100 products and 100 vendors. That's 10,000 loops with 7+ queries, that's at least 70,000 queries. This is not a scalable solution.
Let's look further.. what's in all these "Getxxx" methods? I assume there is some kind of query in each of those? Are you possibly performing double queries each time? Again, you're not including all the information.
To be honest, i'm quite surprised that this ONLY takes 20 seconds... i'd think it would be more like 20 minutes with any amount of data.

Related

how to add linq result to list with key

I have a linq which is inside a for loop,im adding the results to a list using addRange() but it will add whole thing in a single set,for example my first loop result has 16 items,the second has 10 items,...i want them to be added to list like this then i can see in list how many and which items has been added on each query
public List<statisticsDaily> dailyStat(List<string> id,string dtFrom,string dtTo)
{
List<StatisticsDaily> rsltofquery = new List<StatisticsDaily>();
for (int i = 0; i < id.Count; i++)
{
var rslt = (from d in db.statDaily
join s in db.masterData on d.m_turbine_id equals s.m_turbine_id
where d.m_turbine_id == IPAddress.Parse(id[i]) && d.m_date >= frm && d.m_date <= to
select new StatisticsDaily
{
m_wind_speed = d.m_wind_speed,
Date = d.m_date.ToString("yyyy-MM-dd"),
name = s.turbine_name,
Production = d.m_energy_prod,
Availability = d.m_corrected_av
}
).AsEnumerable().OrderBy(s => s.Date).ToList();
rsltofquery.AddRange(rslt);
}
You need to have collection of collections like List<List<StatisticsDaily>>.
So yours code will be:
public List<List<statisticsDaily>> dailyStat(List<string> id,string dtFrom,string dtTo)
{
List<List<StatisticsDaily>> rsltofquery = new List<List<StatisticsDaily>>();
for (int i = 0; i < id.Count; i++)
{
var rslt = (from d in db.statDaily
join s in db.masterData on d.m_turbine_id equals s.m_turbine_id
where d.m_turbine_id == IPAddress.Parse(id[i]) && d.m_date >= frm && d.m_date <= to
select new StatisticsDaily
{
m_wind_speed = d.m_wind_speed,
Date = d.m_date.ToString("yyyy-MM-dd"),
name = s.turbine_name,
Production = d.m_energy_prod,
Availability = d.m_corrected_av
}).AsEnumerable().OrderBy(s => s.Date).ToList();
rsltofquery.Add(rslt);
}
}
If you want to use all elements, not in parts, you can use SelectMany:
var x = dailyStat(id, dtFrom, dtTo);
foreach (var e in x.SelectMany(d => d)) ...

Using savechanges() inside foreach loop c#

I have this method below that is writing data to two tables in the database. There is a collection I need to write to the database in the foreach section. why saveChanges does not work in each iteration of the loop and is there a better way of doing this?
there is two things... first:the function does not return any thing .... second:the database did not up to date .... when i removed savechange() from the function it has works but with out changing values in database .
if (_context.ProductPins.Where(a => a.ProductId == id && a.Status==false).Count() > 0)
{
var c = 0;
var ProductPins = _context.ProductPins.Where(a=>a.Status==false && a.ProductId == id);
foreach(var item in ProductPins)
{
ApplicationUser.Balance = ApplicationUser.Balance - product.BuyingPrice;
item.Equals(true);
_context.Statements.Add(new Statement
{
Amount = product.BuyingPrice,
RecordDate = DateTime.Now,
Destination = false,
FromApplicationUserId = _userManager.GetUserId(User),
//ToApplicationUserId = nu,
BalanceType = BalanceType.currentbalance,
});
_context.Update(ApplicationUser);
_context.Update(item);
_context.SaveChanges();
c++;
if (c > count)
{
break;
}
}
If you are saving to a database, you should queue these changes so that you can do one write at the end and process all of them at once rather than one at a time, this way you take advantage of the databases internal write processing.
I only put savechange() method out of froreach loop....savechanges() should be not inside loop
if (_context.ProductPins.Where(a => a.ProductId == id && a.Status==false).Count() > 0)
{
var c = 0;
var ProductPins = _context.ProductPins.Where(a=>a.Status==false && a.ProductId == id);
foreach(var item in ProductPins)
{
ApplicationUser.Balance = ApplicationUser.Balance - product.BuyingPrice;
item.Equals(true);
_context.Statements.Add(new Statement
{
Amount = product.BuyingPrice,
RecordDate = DateTime.Now,
Destination = false,
FromApplicationUserId = _userManager.GetUserId(User),
//ToApplicationUserId = nu,
BalanceType = BalanceType.currentbalance,
});
_context.Update(ApplicationUser);
_context.Update(item);
c++;
if (c > count)
{
break;
}
}
_context.SaveChanges();

Foreach and querys performance improvement issue in C#

I'm having a problem with performance in my code.
The method below is used to create a comparative score of companies from the whole country based some rules:
public List<object> GetCNAEBRCycleChart(int VisitId)
{
List<object> result = new List<object>();
Visit visit = Context.Visit.Find(VisitId);
Company company = visit.Company;
var CNAE = company.MainEconomicCNAE.IdentifyCNAE;
string[] Themes = new string[5];
Themes[0] = "Finance";
Themes[1] = "Market";
Themes[2] = "Organization";
Themes[3] = "Planning";
Themes[4] = "People";
int count = 0;
List<Visit> listVisitCNAECountry = (from vis in Context.Visit
where vis.Company.MainEconomicCNAE.IdentifyCNAE.StartsWith(CNAE)
&& vis.Order == 1
select vis
).ToList();
double[] Values = new double[5];
Values[0] = 0;
Values[1] = 0;
Values[2] = 0;
Values[3] = 0;
Values[4] = 0;
foreach (var vis in listVisitCNAECountry)
{
count = 0;
var visitIdCompany = vis.Id;
var diagnostic = Context.Visit.Find(visitIdCompany).Diagnostic;
if (diagnostic != null)
{
foreach (var itemTheme in Themes)
{
var TemaAux = itemTema;
int QtQuestion = (from itemForm in Context.FormItem
join tipo in Context.FormItemType on itemForm.FormItemTypeId equals tipo.Id
join itemForm2 in Context.FormItem on itemForm.FormItemParentId equals itemForm2.Id
join itemForm3 in Context.FormItem on itemForm2.FormItemParentId equals itemForm3.Id
where itemForm3.Name == TemaAux && tipo.Name == "Pergunta"
select itemForm
).Count();
var sumAnswerCompany = (from alter in Context.Alternative
join itemForm in Context.FormItem on alter.FormItemId equals itemForm.Id
join itemForm2 in Context.FormItem on itemForm.FormItemParentId equals itemForm2.Id
join itemForm3 in Context.FormItem on itemForm2.FormItemParentId equals itemForm3.Id
join answer in Context.Answer on itemForm.Id equals answer.FormItemId
where answer.AlternativeId == alter.Id &&
answer.DiagnosticId == diagnostico.Id && itemForm3.Name == TemaAux
select alter.Value
).AsEnumerable().Sum();
double scoreCompany = //Some calculations
Values[count] += scoreCompany;
count++;
}
}
}
count = 0;
foreach (var val in Values)
{
Values[count] = //more calculations
count++;
}
var model = new { NameCategory = "CNAE in Country", Value1 = Values[0], Value2 = Values[1], Value3 = Values[2], Value4 = Values[3], Value5 = Values[4] };
result.Add(model);
return result;
}
The problem is that, with the actual CNAE, the list listVisitCNAECountry gets 16000+ elements, which make for terrible performance.
In my localhost environment it's taking 30min+ and I don't even know where to begin to actually improve the performance.
The biggest problem is that I really need all those iterations to make the calculations right.
If anyone has any ideas, please, help me.
The first thing to change is:
var sumAnswerCompany = ( /* complex query */
).AsEnumerable().Sum();
This is bad; instead of issuing select sum(...) as a database query, it instead will have to select the column(s) and return all the rows required, which may be a huge amount of bandwidth.
Instead, do the sum at the database and just bring back one number:
var sumAnswerCompany = ( /* complex query */
).Sum();
However, frankly I'd suggest writing the entire thing in raw SQL using joins and grouping from the original data. Sometimes LINQ isn't your best tool.

Randomly Selected Data from Database with Constraints

I have created a MySQL Database with a vast number of products and their cost. I utilize EF6 to wrap the database.
Based on the given input, I need to generate at random, a correct selection that meets the described criteria.
For example:
10 Items, Total Value $25
I am at a loss as how to properly go about iterating through the database to produce the required results.
What I am currently doing seems terribly inefficent:
using (var db = new Database())
{
var packageSelected = false;
var random = new Random();
var minItemId = (from d in db.products select d.id).Min();
var maxItemId = (from d in db.products select d.id).Max();
var timer = new Stopwatch();
timer.Start();
Console.WriteLine("Trying to make package...");
while (!packageSelected)
{
var currentItems = new List<int>();
for (var i = 0; i <= 9; i++)
{
var randomItem = random.Next(minItemId, maxItemId);
currentItems.Add(randomItem);
}
decimal? packageValue = 0;
currentItems.ForEach(o =>
{
var firstOrDefault = db.products.FirstOrDefault(s => s.id == o);
if (firstOrDefault != null)
{
var value = firstOrDefault.MSRP;
packageValue += value;
}
});
if (!(packageValue >= 25) || !(packageValue <= 26)) continue;
packageSelected = true;
timer.Stop();
Console.WriteLine("Took {0} seconds.", timer.Elapsed.TotalSeconds);
currentItems.ForEach(o =>
{
var firstOrDefault = db.products.FirstOrDefault(s => s.id == o);
if (firstOrDefault != null)
Console.WriteLine("Item: {0} - Price: ${1}", firstOrDefault.DESCRIPTION,
firstOrDefault.MSRP);
});
}
}
What about something like this:
public virtual TEntity GetRandom()
{
return DBSet.OrderBy(r => Guid.NewGuid()).Take(1).First();
}
public List<TEntity> Random(int amount, int maxprice)
{
var list = new List<TEntity>();
var tempPrice = 0;
for (int i = 0 ; i < amount; i++)
{
var element = GetRandom();
tempPrice += element.Price;
if (tempPrice > maxprice)
{
return list;
}
list.Add(element);
}
return list;
}
hope this helps
EDIT: If the maxprice is reached before the required amount of elements, the for-loop will stop and you won't get the full amount of elements.

LINQ to SQL dividing filters for better performance

I have these below LINQ to SQL queries
var kayitlarFiltreli = from rows in db.TBLP1CARIs
orderby rows.ID descending
where rows.HESAPADI.ToLower().Contains(filter.ToLower()) ||
(rows.CARITURU == "Bireysel" ?
rows.B_ADSOYAD.ToLower().Contains(filter.ToLower()) :
rows.K_FIRMAADI.ToLower().Contains(filter.ToLower())) ||
rows.ID.ToString().Contains(filter)
select rows;
var kayitlarBakiyeli = from rows in kayitlarFiltreli
select new
{
HESAPNO = rows.ID,
HESAPADI = rows.HESAPADI,
CARIADI = (rows.CARITURU == "Bireysel" ? rows.B_ADSOYAD : rows.K_FIRMAADI),
Bakiye = get_bakiye(rows.ID, rows.LISTEPARABIRIMI)
};
var kayitlarSon = from rows in kayitlarBakiyeli
select new
{ rows.HESAPNO,
rows.HESAPADI,
rows.CARIADI,
Bakiye = rows.Bakiye.Contains(".") == true ?
rows.Bakiye.TrimEnd('0').TrimEnd('.') :
rows.Bakiye
};
I am having performance problem I mean the queries response at least after 15secs, and when it is deployed to the website it takes at least 5 secs for the page which is using these queries to fill a GridView.get_bakiye(p1,p2,..) is a long method with a for, a foreach and a Linq-to-SQL query in it.I think the most of time is spent on get_bakiye I struggled with it already and reduced the response time like 2 secs, however it is still slow.And I am trying to get the above queries work faster.
I tried
var kayitlarSirali = from rows in db.TBLP1CARIs
orderby rows.ID descending
select rows;
var kayitlarFiltreli = from rows in kayitlarSirali
where rows.HESAPADI.ToLower().Contains(filter.ToLower()) ||
(rows.CARITURU == "Bireysel" ?
rows.B_ADSOYAD.ToLower().Contains(filter.ToLower()) :
rows.K_FIRMAADI.ToLower().Contains(filter.ToLower())) ||
rows.ID.ToString().Contains(filter)
select rows;
And the rest is the same.
Basically I just seperated the filtering part with Contains(), which I am not sure if that helps so much.
Is it good to seperate where's I mean filters when querying the database, and is it better for performance to query the database once and get the results into an in-memory IQueryable and do the rest on it?
What do you recommend for these queries to work faster?
This is the get_bakiye() method which is not something I wrote fully but I am supposed to make it perform faster.
public static string get_bakiye(int cari_id, string birim_kod)
{
return get_bakiye(cari_id, DAL.DAOCari.GetEntity(cari_id).LISTEPARABIRIMI, null,false);
}
public static string get_bakiye(int cari_id, string birim_kod, List<BAL.P_CariBakiyeTablosu> custom_rapor, bool borcluTespit)
{
VeriyazDBDataContext db = new VeriyazDBDataContext(); db.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
decimal return_bakiye = 0;
if (birim_kod == null || birim_kod.Trim() == "") //default
birim_kod = "TL";
//devir bakiyesini hesapla:
List<BAL.P_CariBakiyeTablosu> bakiyeler = new List<BAL.P_CariBakiyeTablosu>();
if (custom_rapor == null)
bakiyeler = CariBakiyeRaporuOlustur(cari_id, true);
else
bakiyeler = custom_rapor;
bakiyeler.RemoveAt(0);
List<TBLP1DOVIZTANIMLARI> dovizTanimlariTumListe = DAL.DAOdoviztanimlari.SelectAll().ToList();
//devirleri hesaplarken döviztanimlari tablosundaki varsayılan kuru kullanıyor
for (int i = 0; i < bakiyeler.Count; i++)
{
if (bakiyeler[i].DOVIZ == birim_kod)
{
return_bakiye = return_bakiye + Convert.ToDecimal(bakiyeler[i].DEVIR);
}
else
{
decimal from_kur = 1;
from_kur = from_kur = dovizTanimlariTumListe.Where(rows => rows.TBLP1DOVIZLER.KOD == bakiyeler[i].DOVIZ).FirstOrDefault().VARSAYILANKUR.GetValueOrDefault(1);
decimal to_kur = 1;
to_kur = dovizTanimlariTumListe.Where(rows => rows.TBLP1DOVIZLER.KOD == birim_kod).First().VARSAYILANKUR.GetValueOrDefault(1);
return_bakiye = return_bakiye + (Convert.ToDecimal(bakiyeler[i].DEVIR) * (from_kur / to_kur));
}
}
//islem bakiyesini hesapla:
var islemler = from rows in db.TBLP1ISLEMs
where
rows.CARI_ID == cari_id &&
rows.TEKLIF.GetValueOrDefault(false) == false &&
rows.SOZLESME.GetValueOrDefault(false) == false &&
(rows.SIPARISDURUMU == "İşlem Tamamlandı" ||
rows.SIPARISDURUMU == "Hazırlanıyor" ||
rows.SIPARISDURUMU == "" ||
rows.SIPARISDURUMU == null)
select rows;
//var dovizKuruOlanIslemler = from dovizKuruRow in db.TBLP1DOVIZKURUs
// select dovizKuruRow.ISLEM_ID;
foreach (var item in islemler)
{
decimal from_kur = 1;
decimal fromKurVarsayilan = 1;
//belirtilen dövizin varsayılanını çekiyor
fromKurVarsayilan = dovizTanimlariTumListe.Where(rows => rows.TBLP1DOVIZLER.KOD == item.PARABIRIMI).FirstOrDefault().VARSAYILANKUR.GetValueOrDefault(1);
try
{
from_kur = item.KURDEGERI.Value;
//aşağıdaki satırda dövizkuru tablosundan işleme ait kuru çekerek hesap yapıyordu, işlem tablosuna KURDEGERİ kolonu ekleyince
//buna gerek kalmadı, yukarıdaki satırda işleme ait kur değeri işlem tablosundan çekiyor.
//from_kur = item.TBLP1DOVIZKURUs.Where(rows => rows.DOVIZBIRIM == item.PARABIRIMI).FirstOrDefault().KUR.GetValueOrDefault();
}
catch
{
from_kur = fromKurVarsayilan;
}
//carinin para biriminin varsayılan kurunu çekiyor
decimal to_kur = 1;
decimal toKurVarsayilan = 1;
toKurVarsayilan = dovizTanimlariTumListe.Where(rows => rows.TBLP1DOVIZLER.KOD == birim_kod).FirstOrDefault().VARSAYILANKUR.GetValueOrDefault(1);
to_kur = toKurVarsayilan;
if (item.CARIISLEMTURU == "BORC")
{
return_bakiye = return_bakiye + (Convert.ToDecimal(item.GENELTOPLAM) * (from_kur / to_kur));
}
if (item.CARIISLEMTURU == "ALACAK")
{
return_bakiye = return_bakiye - (Convert.ToDecimal(item.GENELTOPLAM) * (from_kur / to_kur));
}
}
string returnBakiyeParaFormatli = DAL.Format.ParaDuzenle.ParaFormatDuzenle(return_bakiye.ToString());
if (borcluTespit==true)
{
return return_bakiye.ToString();
}
if (returnBakiyeParaFormatli.Contains(".") == true)
{
return returnBakiyeParaFormatli.TrimEnd('0').TrimEnd('.') + " " + birim_kod;
}
else
{
return returnBakiyeParaFormatli + " " + birim_kod;
}
}
}
In general i think you need to understand what causes Linq to Sql to execute a query against your database. In general, extension methods such as ToList(), First(), FirstOrDefault(), Single() will cause Linq To Sql to execute a command against the database. One line that does concern me is:
List<TBLP1DOVIZTANIMLARI> dovizTanimlariTumListe = DAL.DAOdoviztanimlari.SelectAll().ToList();
This seems to be getting every row from the database table that DAOdoviztanimlari is mapped to. The result of this is then queried in memory.
This then happens for every record in the queries that call get_bakiye()!
Ultimately (perfect world) you want get_bakiye() to not contain any of the extension methods i have mentioned and to return IQueryable<string> then let Linq to SQL descide how it optimizes and executes the SQL.
First profile your database and see how long the generated queries take to execute and how often do they execute.
If the results from the profiling show that you are executing the same query against the database or the query takes too long to execute perhaps you should consider loading values into memory and access them from there. Or even consider compiled queries as an alternative if that's plausible.
I had a similar problem a little while ago that I solved by creating a separate class that handles the loading of values that I needed into a collection and updating the values when necessary.

Categories

Resources