SQL to LINQ (Entity Framework Core) - entity-framework

I am trying to write SQL to LINQ. I tried Linqpad, but this feature is not available (only LINQ to SQL conversion).
I have this SQL query
SELECT
count(*),
count(TireWidth),
count(TireRimDiameter),
count(TireSeason),
count(PriceCzk)
FROM(
SELECT
CASE WHEN TireWidth = 255 THEN 1 END TireWidth,
CASE WHEN TireRimDiameter = 16 AND TireWidth = 255 THEN 1 END TireRimDiameter,
CASE WHEN TireSeason = 1 THEN 1 END TireSeason,
CASE WHEN PriceCzk > 50000 THEN 1 END PriceCzk
FROM Products
)
Products
How can I write this query in LINQ? I am using Entity Framework Core, .NET Core 5.
Thank you advance

Trick is in using group by by constant. EF will create just plain aggregation query.
var query =
from p in ctx.Products
group p by 1 into g
select new
{
Count = g.Count(),
TireWidth = g.Sum(x => x.TireWidth == 255 ? 1 : 0),
TireRimDiameter = g.Sum(x => x.TireRimDiameter == 16 && x.TireWidth == 255 ? 1 : 0),
TireSeason = g.Sum(x => x.TireSeason == 1 ? 1 : 0),
PriceCzk = g.Sum(x => x.PriceCzk > 50000 ? 1 : 0)
};

I didn't find LINQ solution, but this solution is working and very fast:
var MySqlParameters = new List<MySqlParameter>();
MySqlParameters.Add(new MySqlParameter("p_date", DateTime.UtcNow.Date));
MySqlParameters.Add(new MySqlParameter("p_product_type", (int)(parameters.ProductType ?? 0)));
MySqlParameters.AddRange(BuildInParameters("p_condition",
parameters.Conditions.Select(c => (int)c), out var conditionParameters));
MySqlParameters.AddRange(BuildInParameters("p_brand",
parameters.Brands.Select(c => (int)c), out var brandParameters));
MySqlParameters.AddRange(BuildInParameters("p_seller",
parameters.UserTypes.Select(c => (int)c), out var sellerParameters));
if (parameters.ToMileage != null)
MySqlParameters.Add(new MySqlParameter("p_mileage", parameters.ToMileage));
if (parameters.FromPrice != null)
MySqlParameters.Add(new MySqlParameter("p_from_price", parameters.FromPrice));
if (parameters.ToPrice != null)
MySqlParameters.Add(new MySqlParameter("p_to_price", parameters.ToPrice));
if (parameters.TireSeason != null)
MySqlParameters.Add(new MySqlParameter("p_tire_ses", parameters.TireSeason));
if (parameters.TireVehicleType != null)
MySqlParameters.Add(new MySqlParameter("p_veh_type", parameters.TireVehicleType));
if (parameters.TireWidth != null)
MySqlParameters.Add(new MySqlParameter("p_tire_wid", parameters.TireWidth));
if (parameters.TireHeight != null)
MySqlParameters.Add(new MySqlParameter("p_tire_hei", parameters.TireHeight));
if (parameters.TireRimDiameter != null)
MySqlParameters.Add(new MySqlParameter("p_tire_rim", parameters.TireRimDiameter));
if (parameters.TireLoadIndex != null)
MySqlParameters.Add(new MySqlParameter("p_tire_loa", parameters.TireLoadIndex));
if (parameters.TireSpeedRating != null)
MySqlParameters.Add(new MySqlParameter("p_tire_spd", parameters.TireSpeedRating));
if (parameters.FromYear != null)
MySqlParameters.Add(new MySqlParameter("p_car_fromYear", parameters.FromYear));
if (parameters.ToYear != null)
MySqlParameters.Add(new MySqlParameter("p_car_toYear", parameters.ToYear));
var builder = new StringBuilder();
if (isTireWidth)
{
builder.AppendLine($#"UNION ALL
SELECT 'TireWidth' FilterName, TireWidth FilterValue, COUNT(1) as FilterCount FROM
`products` P LEFT OUTER JOIN `aspnetusers` U ON P.UserId=U.Id
WHERE P.Deleted=0 AND TireWidth IS NOT NULL
AND (P.ExpirationDateUtc='0001-01-01' OR P.ExpirationDateUtc >= #p_date)
AND P.ProductType = #p_product_type");
if (conditionParameters != "") builder.AppendLine($"AND P.ProductCondition IN ({conditionParameters})");
if (brandParameters != "") builder.AppendLine($"AND P.Brand IN ({brandParameters})");
if (sellerParameters != "") builder.AppendLine($"AND U.Type IN ({sellerParameters})");
if (parameters.ToMileage != null) builder.AppendLine($"AND P.Mileage <= #p_mileage");
if (parameters.FromPrice != null) builder.AppendLine($"AND P.PriceCzk >= #p_from_price");
if (parameters.ToPrice != null) builder.AppendLine($"AND P.PriceCzk <= #p_to_price");
if (parameters.TireSeason != null) builder.AppendLine($"AND P.TireSeason = #p_tire_ses");
if (parameters.TireVehicleType != null) builder.AppendLine($"AND P.TireVehicleType = #p_veh_type");
//if (parameters.TireWidth != null) builder.AppendLine($"AND P.TireWidth = #p_tire_wid");
if (parameters.TireHeight != null) builder.AppendLine($"AND P.TireHeight = #p_tire_hei");
if (parameters.TireRimDiameter != null) builder.AppendLine($"AND P.TireRimDiameter = #p_tire_rim");
if (parameters.TireLoadIndex != null) builder.AppendLine($"AND P.TireLoadIndex = #p_tire_loa");
if (parameters.TireSpeedRating != null) builder.AppendLine($"AND P.TireSpeedRating = #p_tire_spd");
builder.AppendLine("GROUP BY TireWidth");
}
if (isTireVehicleType)
{
builder.AppendLine($#"UNION ALL
SELECT 'TireVehicleType' FilterName, TireVehicleType FilterValue, COUNT(1) as FilterCount FROM
`products` P LEFT OUTER JOIN `aspnetusers` U ON P.UserId=U.Id
WHERE P.Deleted=0 AND TireVehicleType IS NOT NULL
AND (P.ExpirationDateUtc='0001-01-01' OR P.ExpirationDateUtc >= #p_date)
AND P.ProductType = #p_product_type");
if (conditionParameters != "") builder.AppendLine($"AND P.ProductCondition IN ({conditionParameters})");
if (brandParameters != "") builder.AppendLine($"AND P.Brand IN ({brandParameters})");
if (sellerParameters != "") builder.AppendLine($"AND U.Type IN ({sellerParameters})");
if (parameters.ToMileage != null) builder.AppendLine($"AND P.Mileage <= #p_mileage");
if (parameters.FromPrice != null) builder.AppendLine($"AND P.PriceCzk >= #p_from_price");
if (parameters.ToPrice != null) builder.AppendLine($"AND P.PriceCzk <= #p_to_price");
if (parameters.TireSeason != null) builder.AppendLine($"AND P.TireSeason = #p_tire_ses");
//if (parameters.TireVehicleType != null) builder.AppendLine($"AND P.TireVehicleType = #p_veh_type");
if (parameters.TireWidth != null) builder.AppendLine($"AND P.TireWidth = #p_tire_wid");
if (parameters.TireHeight != null) builder.AppendLine($"AND P.TireHeight = #p_tire_hei");
if (parameters.TireRimDiameter != null) builder.AppendLine($"AND P.TireRimDiameter = #p_tire_rim");
if (parameters.TireLoadIndex != null) builder.AppendLine($"AND P.TireLoadIndex = #p_tire_loa");
if (parameters.TireSpeedRating != null) builder.AppendLine($"AND P.TireSpeedRating = #p_tire_spd");
builder.AppendLine("GROUP BY TireVehicleType");
}
var result = _context.FilterQueries.FromSqlRaw(builder.ToString(), MySqlParameters.ToArray());
return result;

Related

List Null after mapping the data Flutter

This Is my coding for mapping data and filter it by subs class:
Hi i have a problem where is my list is null after it mapping the data so can you help me for this solution
void onUserJobListData(Event e) {
Map data = Map.from(e.snapshot.value);
data?.forEach((a, b) {
print("key " + a);
// int i = _jobs.indexWhere((j) => j.jobId == a);
int i = _jobs == null ? 0 : _jobs.indexWhere((j) => j.jobId == a);
if (i >= 0) {
if (b['notification_date'] != null) {
_jobs[i].matchDetail.notificationDate = b['notification_date'];
}
if (b['status_date'] != null) {
_jobs[i].matchDetail.statusDate = b['status_date'];
}
if (b['event_status'] != null) {
_jobs[i].matchDetail.eventStatus = b['event_status'];
}
if (b['notification_status'] != null) {
_jobs[i].matchDetail.notificationStatus = b['notification_status'];
}
if (b['status'] != null) {
_jobs[i].matchDetail.status = b['status'];
}
}
});
print("Apa apa jerr");
jobState.setJobList(_jobs, JobState.USER_JOB);
}`

Unable to create a constant value of type <object>. Only primitive types or enumeration types are supported in this context

I am using the following code:
public static Grid.GridResult GetExamDetailsForGrid(Grid.GridFilter Filter, int userid, int _user_roleid, int selectedYear,string Tin,string Measure, DateTime? Startdate, DateTime? Enddate)
{
Grid.GridResult _examsEntered = new Grid.GridResult();
using (var entity = new PQRSEntityContainer())
{
((IObjectContextAdapter)entity).ObjectContext.CommandTimeout = 120;
var Measureid = 0;
if(!string.IsNullOrEmpty(Measure))
{
Measureid = entity.tbl_Lookup_Measure.Where(m => m.CMSYear == selectedYear && m.Measure_num == Measure)
.Select(v => v.Measure_ID).FirstOrDefault();
}
var _username = CurrentUser.UserName;
var npi = FileProcessBL.getNPINumber(userid);
var cmsYear = selectedYear != 0 ? selectedYear : 0;
var Newtin= string.IsNullOrEmpty(Tin) ? null : Tin;
var NewStartdate = Startdate ==null ? null : Startdate;
var NewEnddate = Enddate == null ? null : Enddate;
var NewMes= string.IsNullOrEmpty(Measure) ? null : Measure;
var liDetails = (from ex in entity.tbl_Exam.Where(i => i.Physician_NPI == npi && i.CMS_Submission_Year == cmsYear
&& i.Exam_TIN == (Newtin==null?i.Exam_TIN:Newtin)
&& i.Exam_Date >= (NewStartdate == null ? i.Exam_Date : NewStartdate)
&& i.Exam_Date <= (NewEnddate == null ? i.Exam_Date : NewEnddate))
from exmes in entity.tbl_Exam_Measure_Data.Where(i => i.Exam_Id == ex.Exam_Id
&& i.Measure_ID== (Measureid == 0 ? i.Measure_ID : Measureid) ).DefaultIfEmpty()
from nume in entity.tbl_lookup_Numerator_Code.Where(nume => exmes.tbl_Lookup_Measure.Measure_ID == nume.tbl_Lookup_Measure.Measure_ID && exmes.Numerator_response_value == nume.Numerator_response_Value).DefaultIfEmpty()
join sc in entity.tbl_Lookup_Data_Source on ex.DataSource_Id equals sc.DataSource_Id
where exmes.Exam_Id != null
select new MesCasesGrid
{
NPI = ex.Physician_NPI,
TIN = ex.Exam_TIN == null ? "" : ex.Exam_TIN,
ExamID = ex.Exam_Id,
//MeasureID = exMes.Measure_ID,
MeasureID = (exmes != null) ? exmes.Measure_ID : 0,
MeasureNum = (exmes != null) ? exmes.tbl_Lookup_Measure.Measure_num : null,
CPTCode = (exmes != null) ? exmes.Denominator_proc_code : null,
///NumeratorCode = (exmes!=null)?exmes.tbl_Lookup_Measure.tbl_lookup_Numerator_Code.Select(i=>i.Numerator_Code).FirstOrDefault():null,
NumeratorCode = nume.Numerator_Code,
Created_Date = ex.Created_Date,
ExamDate = ex.Exam_Date,
UniqueExamID = ex.Exam_Unique_ID,
PatientGender = (ex.Patient_Gender == "M" ? "Male" : ex.Patient_Gender == "F" ? "Female" : ex.Patient_Gender == "O" ? "Other" : ex.Patient_Gender == "U" ? "Unknown" : ""),
PatientID = ex.Patient_ID,
isEncrypt = ex.IsEncrypt,
PatientAge = ex.Patient_Age,
StatusDesc = (exmes != null) ? exmes.tbl_Lookup_Measure_Status.Status_Desc : null,
///Type =ex.DataSource,
Type = sc.DataSource,
cmsYear = ex.CMS_Submission_Year
}).Distinct().ToList();
if (_user_roleid == Constants.FacilityAdminID || _user_roleid == Constants.FacilityUserID || _user_roleid == Constants.RegistryAdminID
|| _user_roleid == Constants.SuperCorporateAdminID || _user_roleid == Constants.CorporateAdminID || _user_roleid == Constants.ServiceUserID) // jira-579
{
var facilityTins = entity.sp_getFacilityTIN(_username).Select(x => x.TIN).ToList();
liDetails = liDetails.Where(i => facilityTins.Contains(i.TIN)).Select(x => x).Distinct().ToList();
}
var value = Convert.ToBoolean(1);
foreach (var item in liDetails)
{
if (item.isEncrypt == value && item.PatientID != null)
{
try
{
var patidDecrypt = AesHelper.Decrypt256(item.PatientID);
item.PatientID = patidDecrypt;
}
catch (Exception ex)
{
}
}
}
return _examsEntered;
}
}
I have recently added the following code above method:
i.Measure_ID == && i.Measure_ID== (Measureid == 0 ? i.Measure_ID : Measureid)
When adding the highlighted code to this method I am getting following error:
:Error in RecordEnteredGridBind()
System.NotSupportedException: Unable to create a constant value of type 'DAL.Entities.tbl_Exam_Measure_Data'. Only primitive types or enumeration types are supported in this context.
at System.Data.Objects.ELinq.ExpressionConverter.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator1.Translate(ExpressionConverter parent, Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Objects.ELinq.ExpressionConverter.NewArrayInitTranslator.<>c__DisplayClass1_0.<TypedTranslate>b__0(Expression e)
at System.Linq.Enumerable.WhereSelectEnumerableIterator2.MoveNext()
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator3.Validate(IEnumerable1 argument, String argumentName, Int32 expectedElementCount, Boolean allowEmpty, Func3 map, Func2 collect, Func3 deriveName)
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator3.Validate()
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.CreateExpressionList(IEnumerable1 arguments, String argumentName, Boolean allowEmpty, Action2 validationCallback)
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateNewCollection(IEnumerable`1 elements, DbExpressionList& validElements)
I have tried lot of ways but not working. So, Can anyone help me?

EF other way to Sum() new Column

i got stuck on this query that calculate the new column.
i cannot explain briefly just see the snippet code below.
from user in context.Table
select new
{
Total = user.Total,
Paid = user.Paid,
Balance = //should be Total - Paid to assign result
}
i have tried this query
var result = from a in context.EnrollmentRequests
where a.SchoolYear == SchoolYear
select new
{
a.StudentID,
Name = a.Student.FirstName + " " + a.Student.MiddleName + " " + a.Student.LastName,
Tuition = context.Miscs.Where(m => m.YearLevel == a.YearLevel && m.SchoolYear == SchoolYear && m.Term == a.Term && m.CourseID == a.CourseID)
.Select(ms => new { Amount = ms.Amount })
.Union(context.StudentCharges
.Where(s => s.YearLevel == a.YearLevel && s.SchoolYear == SchoolYear && s.Term == a.Term && s.CourseID == a.CourseID && s.StudentID == a.StudentID)
.Select(ss => new { Amount = ss.Amount }))
.Union(context.StudentSubjectTakes
.Where(st => st.StudentID == a.StudentID && st.SchoolYear == a.SchoolYear && st.Term == a.Term && st.YearLevel == a.YearLevel && st.EducationalLevel == a.Student.StudentAdvanceEducations.FirstOrDefault().EducationLevel)
.Select(st => new
{
Amount = context.SubjectOfferedFees
.Where(f => f.SubjectsOfferedID == st.SubjectsOfferedID).Sum(w => (decimal?)w.Cost ?? 0)
}))
.Select(f => f.Amount).Sum(),
PaymentMade = context.Payments.Where(p => p.SchoolYear == SchoolYear && p.Term == a.Term && p.StudentID == a.StudentID && p.PaymentDes == "Tuition Fee").Sum(sm => (decimal?)sm.Amount),
Balance = Tuition - PaymentMade //Does not exist on current context
};
but doesn't work it says that does not exist on current context.
how could this possible.
thanks. this will be helpful to anyone.
Balance = user.Total - user.Paid

How to reduce code in a JPA CriteriaBuilder

I'm new to JPA with the CriteriaBuilder and want to reduce some lines of code.
cb.and is usefull to add predicate's, but what if they are null?
How can I reduce these lines of code? Thanks!
I'm worried about the readability of the code...
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(OrganizationEntity.class);
Root<OrganizationEntity> root = cq.from(OrganizationEntity.class);
Predicate predicateFrom = null;
Predicate predicateTo = null;
if (from != null) {
predicateFrom = cb.ge(root.get(OrganizationEntity_.id), from);
}
if (to != null) {
predicateTo = cb.le(root.get(OrganizationEntity_.id), to);
}
if(predicateFrom != null && predicateTo != null) {
cq.where(cb.and(predicateFrom,predicateTo));
} else if (predicateFrom != null && predicateTo == null) {
cq.where(predicateFrom);
} else if (predicateFrom == null && predicateTo != null) {
cq.where(predicateTo);
}
TypedQuery<OrganizationEntity> query = em.createQuery(cq);
list = query.getResultList();
return list;
what you could do is create your predicate list
List<Predicate> predicates = new ArrayList<>();
if (from != null) {
predicates .add(cb.ge(root.get(OrganizationEntity_.id), from));
}
if (to != null) {
predicates .add(cb.le(root.get(OrganizationEntity_.id), to));
}
if (predicates.size()>0{
cq.where(cb.and(predicates.toArray(new Predicate[predicates
.size()])));
}

Is it a lazy loading query or Eager Loading ? , Slow Query, Performance needed please

First, I would like to know if this query is Lazy loading or Eager loading. I Read a lot on both, and not sure if I understand the difference between each other.
2- I Get this query, This query take a lot of time to execute. Anybody have some suggest when you see this query. I'll do all modification needed to speed up this query.
Note: I just want your opinion about this query and method.
Thanks a lot.
public SearchLocationViewModel GetSearchLocationViewModel( string CivicNumber = null ,
string Street = null,
string City = null,
List<int?> ListCountryID = null,
List<int?> ListStateID = null,
int IsActive =1,
string SortField ="FileNumber",
string SortDirection = "asc" ,
List<int?> GrpDescID1 = null,
List<int?> GrpDescID2 = null,
List<int?> GrpDescID3 = null,
List<int?> GrpDescID4 = null,
int LocationTypeID = -1,
List<int?> ListUsageID = null)
{
if (GrpDescID1 == null)
{
GrpDescID1 = new List<int?>();
}
if (GrpDescID2 == null)
{
GrpDescID2 = new List<int?>();
}
if (GrpDescID3 == null)
{
GrpDescID3 = new List<int?>();
}
if (GrpDescID4 == null)
{
GrpDescID4 = new List<int?>();
}
if (ListCountryID == null)
{
ListCountryID = new List<int?>();
}
if (ListStateID == null)
{
ListStateID = new List<int?>();
}
if (ListUsageID == null)
{
ListUsageID = new List<int?>();
}
GrpDescID1.Remove(GrpDescID1.SingleOrDefault(p => p < 0));
GrpDescID2.Remove(GrpDescID2.SingleOrDefault(p => p < 0));
GrpDescID3.Remove(GrpDescID3.SingleOrDefault(p => p < 0));
GrpDescID4.Remove(GrpDescID4.SingleOrDefault(p => p < 0));
ListCountryID.Remove(ListCountryID.SingleOrDefault(p => p < 0));
ListStateID.Remove(ListStateID.SingleOrDefault(p => p < 0));
ListUsageID.Remove(ListUsageID.SingleOrDefault(p => p < 0));
int lang = BaseStaticClass.CurrentLangID();
int UserID = Convert.ToInt32(Session["UserID"]);
SearchLocationViewModel ViewModel = InitSearchViewModel();
IGrpRepository repGrp = new GrpRepository(_db);
ICountryRepository repCountry = new CountryRepository(_db);
IProvinceRepository repProvince = new ProvinceRepository(_db);
ViewModel.Perm = repPermission;
ViewModel. CivicNumber = CivicNumber ;
ViewModel. Street = Street;
ViewModel. City = City;
ViewModel. IsActive =IsActive;
ViewModel. SortField =SortField;
ViewModel. SortDirection = SortDirection ;
ViewModel.ListCountry = repCountry.GetCountryForSearchByUser(true,UserID);
ViewModel.ListProvince = repProvince.GetProvinceSearchByUserID(true, UserID);
ViewModel.ListGrpDescID1 =GrpDescID1;
ViewModel.ListGrpDescID2 = GrpDescID2;
ViewModel.ListGrpDescID3 = GrpDescID3;
ViewModel.ListGrpDescID4 = GrpDescID4;
ViewModel.ListCountryID = ListCountryID;
ViewModel.ListStateID = ListStateID;
ViewModel.LocationTypeID = LocationTypeID;
ViewModel.ListUsageID = ListUsageID;
var LocationType = new SelectList(repGeneric.GetTextByCurrentLang<LocationType, LocationTypeText>(), "ID", "Txt").ToList();
bc.AddDropdownSearchValueNoNew(ref LocationType);
var ListUsage = new SelectList(repGeneric.GetTextByCurrentLang<Usage, UsageText>(), "ID", "Txt").ToList();
ViewModel.ListUsage = ListUsage;
ViewModel.ListLocationType = LocationType;
var ListGrp1 = new SelectList(repGrp.GetAllGrpDescTextForUserByLevel(UserID, 1).AsEnumerable(), "GrpDescID", "GrpDescTxt").ToList();
var ListGrp2 = new SelectList(repGrp.GetAllGrpDescTextForUserByLevel(UserID, 2).AsEnumerable(), "GrpDescID", "GrpDescTxt").ToList();
var ListGrp3 = new SelectList(repGrp.GetAllGrpDescTextForUserByLevel(UserID, 3).AsEnumerable(), "GrpDescID", "GrpDescTxt").ToList();
var ListGrp4 = new SelectList(repGrp.GetAllGrpDescTextForUserByLevel(UserID, 4).AsEnumerable(), "GrpDescID", "GrpDescTxt").ToList();
var t1 = ListGrp1.Select(s => (int?)Convert.ToInt32(s.Value));
var t2 = ListGrp2.Select(s => (int?)Convert.ToInt32(s.Value));
var t3 = ListGrp3.Select(s => (int?)Convert.ToInt32(s.Value));
var t4 = ListGrp4.Select(s => (int?)Convert.ToInt32(s.Value));
ViewModel.ListGrp1 = ListGrp1;
ViewModel.ListGrp2 = ListGrp2;
ViewModel.ListGrp3 = ListGrp3;
ViewModel.ListGrp4 = ListGrp4;
ViewModel.ListGrpTogether = new List<SelectListItem>();
if(ViewModel.GrpName1 != "")
ViewModel.ListGrpTogether.Add(new SelectListItem() { Text = ViewModel.GrpName1 ,Value = "1"});
if (ViewModel.GrpName2 != "")
ViewModel.ListGrpTogether.Add(new SelectListItem() { Text = ViewModel.GrpName2, Value = "2" });
if (ViewModel.GrpName3 != "")
ViewModel.ListGrpTogether.Add(new SelectListItem() { Text = ViewModel.GrpName3, Value = "3" });
if (ViewModel.GrpName4 != "")
ViewModel.ListGrpTogether.Add(new SelectListItem() { Text = ViewModel.GrpName4, Value = "4" });
ViewModel.ListGrpTogether.Insert(0, new SelectListItem() { Text = ViewRes.GeneralString.Choose, Value = "-1", Selected = true });
int iUserID = Convert.ToInt32(Session["UserID"]);
//this is use for Permission
//Get all the user permission about group and province
IEnumerable<int?> usrGrpDesc = _db.UserGroupDescs.Where(p => p.UserID == iUserID).Select(s => s.GrpDescID);
IEnumerable<int?> usrProvince = _db.UserProvinces.Where(p => p.UserID == iUserID).Select(s => s.PrvID);
var ListLocation = from s in _db.Locations.Where(p =>
p.IsDelete == false &&
(IsActive < 0 || IsActive == (p.IsActive == true ? 1 : 0)) &&
(LocationTypeID < 0 || LocationTypeID == p.LocationTypeID) &&
(City == null || p.Address.City.CityName.Contains(City)) &&
(ListUsageID.Count() == 0 || p.Premises.Select(gs => gs.UsageID).Intersect(ListUsageID).Any()) &&
(ListCountryID.Count() == 0 || ListCountryID.Any(pl => pl == p.Address.City.Province.Country.CtryID)) &&
(ListStateID.Count() == 0 || ListStateID.Any(pl => pl == p.Address.City.Province.PrvID)) &&
(Street == null || p.Address.Street.Contains(Street)) &&
(CivicNumber == null || p.Address.CivicNumber.Contains(CivicNumber)) &&
((GrpDescID1.Count() == 0 )|| p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(GrpDescID1).Any()) &&
((GrpDescID2.Count() == 0)|| p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(GrpDescID2).Any()) &&
((GrpDescID3.Count() == 0) || p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(GrpDescID3).Any()) &&
((GrpDescID4.Count() == 0 ) || p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(GrpDescID4).Any()) &&
(p.GroupLocations.Select(gs => gs.GrpDescID).Intersect(usrGrpDesc).Any()) &&
((p.Address.City == null || usrProvince.Any(ps => ps.Value == p.Address.City.PrvID)))
)
select new LocationViewModel()
{
LocationID = s.LocationID,
LocationTypeID = s.LocationTypeID,
Long = s.Address.Longitude,
Lat = s.Address.Latitude,
FileNumber = s.LocationFile,
State = s.Address.City.Province.PrvName,
City = s.Address.City.CityName,
Address = s.Address.CivicNumber + " " + s.Address.Street,
Status = s.LocationType.LocationTypeTexts.Where(h => h.Txt != "" && h.LangID == lang || h.LangID == 1).OrderByDescending(g => g.LangID).FirstOrDefault().Txt,
ListGroupe1 = s.GroupLocations.Where(g=>g.GrpDesc.Grp.GrpLevel == 1).Select(grpLoc => grpLoc.GrpDesc.GrpDescTexts.Where(h => h.GrpDescTxt != "" && (h.LangID == lang || h.LangID == 1)).OrderByDescending(g => g.LangID).FirstOrDefault()).Select(txt => txt.GrpDescTxt),
ListGroupe2 = s.GroupLocations.Where(g => g.GrpDesc.Grp.GrpLevel == 2).Select(grpLoc => grpLoc.GrpDesc.GrpDescTexts.Where(h => h.GrpDescTxt != "" && (h.LangID == lang || h.LangID == 1)).OrderByDescending(g => g.LangID).FirstOrDefault()).Select(txt => txt.GrpDescTxt),
ListGroupe3 = s.GroupLocations.Where(g=>g.GrpDesc.Grp.GrpLevel == 3).Select(grpLoc => grpLoc.GrpDesc.GrpDescTexts.Where(h => h.GrpDescTxt != "" && (h.LangID == lang || h.LangID == 1)).OrderByDescending(g => g.LangID).FirstOrDefault()).Select(txt => txt.GrpDescTxt),
ListGroupe4 = s.GroupLocations.Where(g=>g.GrpDesc.Grp.GrpLevel == 4).Select(grpLoc => grpLoc.GrpDesc.GrpDescTexts.Where(h => h.GrpDescTxt != "" && (h.LangID == lang || h.LangID == 1)).OrderByDescending(g => g.LangID).FirstOrDefault()).Select(txt => txt.GrpDescTxt),
DefaultImgPath = s.LocationPictures.Where(p=>p.IsDefault == true && p.IsActive == true).FirstOrDefault().FilePath,
HasPremises = s.Premises.Any(p => p.IsActive == true && p.IsDelete == false)
};
ViewModel.ListLocation = ListLocation.ToList();
return ViewModel;
}
Lazy loading is deferring initialization of an object until the point at which it is needed. If you returned your ListLocation back to its caller, as you've written above, with no .ToList() (or other), then you'd be consuming this lazily.
Eager loading is having the results of your query gathered at the time that the query is defined. In this case it'd be retrieving the results of your LINQ query all at once (at the time that the query is constrcuted). Usually a .ToList() or .Single() or other will do this for you.
I suspect you're consuming the results your LINQ query (var ListLocation) later in your code. Your code above is using a lazy-loaded approach.
You're showing that you're calling .ToList(), so you're indeed using eager-loading; even though it's on a different statement/line of code.
Performance: I'm not 100% on this being your perf problem, but I'd refactor your LINQ into something like this, using an extension method .WhereIf(). It's a heck of a lot easier to read and write.
var ListLocation = from s in _db.Locations
.Where(p => p.IsDelete == false)
.WhereIf(IsActive >= 0, p=> IsActive == (p.IsActive == true ? 1 : 0))
.WhereIf(LocationTypeID >= 0, p=> LocationTypeID == p.LocationTypeID
.WhereIf(City!=null, p=> p.Address.City.CityName.Contains(City)) //etc
If you're using this, and it works, then you're probably lazy loading, since you don't have any calls to .Include().