Polars: Parallelizing creating a new dataframe while using groupby of another dataframe - python-polars

I have an artifacts dataframe which I need to groupby some columns. This sub-dataframe is then passed to a function where I create a new dataframe.
for sub_df in merged_dataset.groupby(['PRODUCT','PROGRAM','TESTSUITE','MODULE', 'BASECLASS', 'SUBCLASS']):
flow_summary_df = sub_df.select(['PRODUCT','PROGRAM','TESTSUITE','MODULE', 'BASECLASS', 'SUBCLASS', 'VERSION', 'RELEASE_DATE', 'Status'])
current_test_events_dataset = add_test_events(flow_summary_df)
Here is the add_test_events code:
def add_test_events_new(flow_summary_df):
previous_test_status = None
known_versions = flow_summary_df.VERSION.to_list()
test_events = []
test_event_versions = []
test_events_data = {}
for i, version in enumerate(known_versions):
if i == 0:
test_events.append('Introduced')
test_event_versions.append(version)
if flow_summary_df.Status[i] == 'BINNING':
test_events.append('Binning Enabled')
test_event_versions.append(version)
previous_test_status = flow_summary_df.Status[i]
continue
if flow_summary_df.Status[i] == 'BYPASSED' and previous_test_status != 'BYPASSED':
test_events.append('Removed')
test_event_versions.append(version)
previous_test_status = 'BYPASSED'
elif flow_summary_df.Status[i] == 'BINNING' and previous_test_status != 'BINNING':
test_events.append('Binning Enabled')
test_event_versions.append(version)
previous_test_status = 'BINNING'
elif flow_summary_df.Status[i] == 'NON-BINNING' and previous_test_status == 'BINNING':
test_events.append('Binning Disabled')
test_event_versions.append(version)
previous_test_status = 'NON-BINNING'
elif flow_summary_df.Status[i] != 'BYPASSED' and previous_test_status == 'BYPASSED':
test_events.append('Re-Introduced')
test_event_versions.append(version)
if flow_summary_df.Status[i] == 'BINNING':
test_events.append('Binning Enabled')
for column in ['PRODUCT','PROGRAM','TESTSUITE','MODULE', 'BASECLASS', 'SUBCLASS', 'VERSION', 'RELEASE_DATE', 'TEST_EVENT']:
if column == 'TEST_EVENT':
test_events_data[column] = test_events
elif column == 'VERSION':
test_events_data[column] = test_event_versions
else:
if flow_summary_df[column][0] is None:
test_events_data[column] = [''] * len(test_events)
else:
test_events_data[column] = [flow_summary_df[column][0]] * len(test_events)
test_events_df = pl.DataFrame(test_events_data)
return test_events_df
It just feels like this is not the polars way to do things.
thx

Related

SQL to LINQ (Entity Framework Core)

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;

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?

Inconsistent indent QGIS

I try to set some qwidgets on fields in a Qgis Project, but i have an error of inconsistent dedent at elif field.name() == 'syst':. Made so far:
def load(self):
map_layers = iface.legendInterface().layers()
for layer in map_layers:
if layer.name() == 'MAT_CANA':
mat_canaId = layer.id()
elif layer.name() == 'Collecteur':
CollecteurId = layer.id()
elif layer.name() == 'FORME_CHAMBRE':
FormeChambreId = layer.id()
elif layer.name() == 'Genre_Chambre':
GenreChambreId = layer.id()
elif layer.name() == 'MAT_CHMB_COU':
MaterialChambreCouId = layer.id()
elif layer.name() == 'PRECISION':
PrecisionId = layer.id()
elif layer.name() == 'SYSTEM_ECOULE':
SystemEcouleId = layer.id()
for layer in map_layers:
if '"public"."chambre_eau_provisoire"' in layer.source():
layer.setEditForm('C:/Users/george.vina/Desktop/BOUDRY/Forme/formeUi/chambrePr.ui')
fields = layer.pendingFields()
for field in fields:
if field.name() == 'genre_cham':
fieldIndex = layer.fieldNameIndex('genre_cham')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': GenreChambreId,'Key': 'genre_chambre', 'Value': 'genre_chambre'})
elif field.name() == 'syst':
fieldIndex = layer.fieldNameIndex('syst')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': SystemEcouleId,'Key': 'system_ecoule', 'Value': 'system_ecoule'})
elif field.name() == 'type_chamb':
fieldIndex = layer.fieldNameIndex('type_chamb')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': FormeChambreId,'Key': 'forme_chambre', 'Value': 'forme_chambre'})
elif field.name() == 'mat_chamb':
fieldIndex = layer.fieldNameIndex('mat_chamb')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': MaterialChambreCouId,'Key': 'mat_chmb_cou', 'Value': 'mat_chmb_cou'})
elif field.name() == 'type_couve':
fieldIndex = layer.fieldNameIndex('type_couve')
layer.setEditorWidgetV2(fieldIndex,'ValueRelation')
layer.setEditorWidgetV2Config(fieldIndex,{'Layer': MaterialChambreCouId,'Key': 'mat_chmb_cou', 'Value': 'mat_chmb_cou'})

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

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().