LINQ to Entities: nullable datetime in where clause - c#

I have a where clause that looks up child objects on an entity:
var Lookup = row.Offenses.Where(x => x.Desc == co.Desc && x.Action == co.Action && x.AppealYN == co.AppealYN && x.OffDate == co.OffDate).ToList();
Sometimes the co.OffDate can be null, which will cause an exception. Right now, the only way I can think of to get around that, is to use an if statement:
if (co.OffDate.HasValue)
{
var Lookup = row.Offenses.Where(x => x.Desc == co.Desc && x.Action == co.Action && x.AppealYN == co.AppealYN && x.OffDate == co.OffDate).ToList();
}
else
{
var Lookup = row.Offenses.Where(x => x.Desc == co.Desc && x.Action == co.Action && x.AppealYN == co.AppealYN).ToList();
}
Is there anyway I can re-write the linq query to accomplish what the if statement does? I still want to do a lookup, even if the co.OffDate is null.

You could insert a ternary into your Where filter:
var Lookup = row.Offenses
.Where(x =>
x.Desc == co.Desc
&& x.Action == co.Action
&& x.AppealYN == co.AppealYN
&& (co.OffDate.HasValue ? x.OffDate == co.OffDate : true)
).ToList();

I would rewrite it to be more readable (in my opinion):
var query = row.Offenses.Where(x => x.Desc == co.Desc
&& x.Action == co.Action
&& x.AppealYN == co.AppealYN)
if (co.OffenseDate.HasValue)
{
query = query.Where(x.OffDate == co.OffenseDate);
}
var Lookup = query.ToList();

Related

EntityFremework: could a select before a where optimize this?

I'm trying to gain performance on this query, and I'd like to know if calling a Select() before the Where() I could have some improvement:
public async Task<List<PostValues>> GetValuesToTheDashboard(DataFilter filter, CancellationToken cancellationToken) {
long startTimestanp = Helpers.UnixTimeNow(filter.StartDate);
long endTimestanp = Helpers.UnixTimeNow(filter.EndDate);
return await
_context.CatchDetails.Where(
x => x.Monitoring.Client.Id == filter.CustomerId && x.Data.published >= startTimestanp
&& x.Data.published <= endTimestanp
&& ((filter.Sentiment == Sentiments.ALL) || x.Sentiment_enum == filter.Sentiment)
&& (filter.MonitoringId == 0 || x.Monitoring.id == filter.MonitoringId)
&& (filter.KeywordId == 0 || x.Keyword.Id == filter.KeywordId)
&& (filter.MotiveId == 0 || x.Motive.Id == filter.MotiveId)
&& (filter.SocialNetwork.Count == 0 || filter.SocialNetwork.Any(s => x.Data.social_media == s))
&& (filter.Busca == "" || x.Data.content_snippet.Contains(filter.Busca))
&& (filter.Gender.Count == 0 || filter.Gender.Any(g => x.Data.extra_author_attributes.gender_enum == g)))
.Select(s => new PostValues() {
CatchDetailsId=s.Id,
Monitoring=s.Monitoring.name,
Keyword=s.Keyword.Text,
Motive=s.Motive.Name,
Sentiment=s.Sentiment_enum,
Gender=s.Data.extra_author_attributes.gender_enum,
SocialMedia=s.Data.social_media,
Country=s.Data.extra_author_attributes.world_data.country_code,
State=s.Data.extra_author_attributes.world_data.region,
Published=s.Data.published
}).ToListAsync(cancellationToken);
}
There might be a way how to improve performance, but it won't be with switching Select and Where (as Chetan mentioned in the comment).
You could build the query in a sequence and based on the filter get a simpler query in the end. This would go like this:
var query = _context.CatchDetails.Where(
x => x.Monitoring.Client.Id == filter.CustomerId && x.Data.published >= startTimestanp
&& x.Data.published <= endTimestanp);
if (filter.Sentiment != Sentiments.ALL)
{
query = query.Where(x => x.Sentiment_enum == filter.Sentiment);
}
if (filter.MonitoringId != 0)
{
query = query.Where(x => x.Monitoring.id == filter.MonitoringId);
}
[...]
return await
query.Select(s => new PostValues() {
[...]
}).ToListAsync(cancellationToken);
Do not forget, the variable query is already on memory of the application when the SQL returns data. If there is many results it could throw memory exception.
I suggest that you limit the range of date on that search.

LINQ2SQL doesn't return row if checking with null

I have following LINQ2SQL Query:
var map =
dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == tcpDms.FacilityId &&
c.DriverControlledParameterId == controlledParamId &&
c.DriverValue == value);
All the types are string.
In my DB i have a row, which must be returned by query.
When value="0", controlledParamId =null and FacilityId ="abc" this query returns null, but when i wrote following:
var test = dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == "abc" &&
c.DriverControlledParameterId == null &&
c.DriverValue == "0");
test was not null
What am i doing wrong?
P.S. I also tried c.DriverControlledParameterId.Equals(controlledParamId) but it also doesn't work.
The problem is, that LINQ2SQL has a special handling for the expression c.DriverControlledParameterId == null. It is translated to the SQL DriverControlledParameterId IS NULL.
But c.DriverControlledParameterId = controlledParamId is translated to the SQL DriverControlledParameterId = :p1, even when controlledParamId is null. And in SQL DriverControlledParameterId = NULL is undefined and as such never TRUE.
How to fix: Handle the null case specifically:
TCPDriverMapping test;
if(controlledParamId == null)
test = dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == "abc" &&
c.DriverControlledParameterId == null &&
c.DriverValue == "0");
else
test = dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == "abc" &&
c.DriverControlledParameterId == controlledParamId &&
c.DriverValue == "0");
Or like this:
var test = dbContext.TCPDriverMappings.FirstOrDefault(
c => c.DriverFacilityId == "abc" &&
((controlledParamId == null &&
c.DriverControlledParameterId == null) ||
c.DriverControlledParameterId == controlledParamId) &&
c.DriverValue == "0");
Or like this:
IQueryable<TCPDriverMapping> query =
dbContext.TCPDriverMappings.Where(c => c.DriverFacilityId == "abc" &&
c.DriverValue == "0");
if(controlledParamId == null)
query = query.Where(c => c.DriverControlledParameterId == null);
else
query = query.Where(c => c.DriverControlledParameterId == controlledParamId);
var test = query.FirstOrDefault();
That third option is what I would use. In my opinion, this is the more readable than option 2 and has no repeated code like the first one.

can i make a this linq statement iteration from a collection in a single statement?

bool isExist = objCustomization.CustomSettings.Where(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID).Any();
if (isExist)
{
chkFixLimit.Checked = objCustomization.CustomSettings.Where(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID).FirstOrDefault().IsDefaultLimit;
}
else chkFixLimit.Checked = false;
Default value for boolean is false so you even don't need any conditions - just select first or default IsDefaultLimit value:
chkFixLimit.Checked =
objCustomization.CustomSettings
.Where(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID)
.Select(p => p.IsDefaultLimit)
.FirstOrDefault();
UPDATE (answer for your comment) in case you have non-boolean value or default value (zero for integer) do not fit your requirements, with DefaultIfEmpty you can provide own default value if there is no items matching your condition:
maxCountCmb.SelectedIndex =
objCustomization.CustomSettings
.Where(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID)
.Select(p => p.DefaultFreeCount)
.DefaultIfEmpty(-1)
.First();
Sure you can:
var item = objCustomization.CustomSettings.FirstOrDefault(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID);
chkFixLimit.Checked = item != null && item.IsDefaultLimit;
Or single statement, as you wish:
chkFixLimit.Checked = new Func<bool>(() => {
var item = objCustomization.CustomSettings.FirstOrDefault(p => p.CustomizationType == selCustomizationType && p.CategoryID == selCategoryID);
return item != null && item.IsDefaultLimit;
}).Invoke();
chkFixLimit.Checked = objCustomization.CustomSettings
.Where(p => p.CustomizationType == selCustomizationType
&& p.CategoryID == selCategoryID)
.Select(c => c.IsDefaultLimit)
.FirstOrDefault();
This not in one line but it is more readable, you can change:
var setting = objCustomization.CustomSettings
.FirstOrDefault(p => p.CustomizationType == selCustomizationType
&& p.CategoryID == selCategoryID);
chkFixLimit.Checked = setting == null ? false : setting.IsDefaultLimit;
That code is more-or-less the use case of the FirstOrDefault method. If something exists, return the first such item, and return a default value (null for reference types) if it doesn't. So you could just do:
var item = objCustomization.CustomSettings.FirstOrDefault
(p => p.CustomizationType == selCustomizationType && p.CategoryID)
and as result, the item object will either be null (assuming you indeed work with a reference type), or it will have a value.
After that you can just check that, with a simple
chkFixLimit.Checked = (item == null) ? false : item.IsDefaultLimit;

Cannot implicitly convert type System.Collections.Generic.IEnumerable<> to bool

I'm developing an ASP.NET MVC 4 Application and I'm trying to run this Lambda expression in Entity Framework 5.
var customer = db.GNL_Customer.Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
.Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
.Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
.Where(d => d.GNL_CustomerLaptopProduct.Where(r => String.Compare(r.BrandName, brandID) == 0 || brandID == null));
I get this error :
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<ITKaranDomain.GNL_CustomerLaptopProduct>' to 'bool'
I know that the last where clause is wrong but I don't know how to correct it.
You might want another .Any instead of a .Where in your .Any clause at the end:
var customer = db.GNL_Customer.Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
.Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
.Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
.Any(d => d.GNL_CustomerLaptopProduct.Any(r => String.Compare(r.BrandName, brandID) == 0 || brandID == null));
Use Where ( Any ) in last statement to select customers which have at least one product satisfying your conditions:
var customer = db.GNL_Customer
.Where(d => d.GNL_City.FKProvinceID == advancedProvinceID || advancedProvinceID == null)
.Where(d => d.FKCityID == advancedCityID || advancedCityID == null)
.Where(d => d.FKDepartmentStoreID == advancedDepartmentStoreID || advancedDepartmentStoreID == null)
.Where(d => brandID == null || d.GNL_CustomerLaptopProduct.Any(r => r.BrandName == brandID));

Nullable Parameter used in Lambda Query is being ignored

I'm trying to pass a null value from a RenderAction to another view. But in between, at the controller, my linq lambda expression is not loading the right field, despite the null value going through correctly..
SprintManager.cshtml
<div id="Global_Backlog_Board" class="Board_Panel">
#{Html.RenderAction("ListOfSingleCards", new
{
State_ID = 1
});}
</div>
HomeController.cs
public PartialViewResult ListOfSingleCards( int? Sprint_ID,
int State_ID = 1)
{
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
return PartialView(Cards);
}
So Sprint_ID is being passed over and loaded as null here, but I can't get the query to load the rows correctly.
In fact, the following works:
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
So I suppose I could check if Sprint_ID is null and depending on the result run one of the two seperate queries, but I'd like to understand why my original attempt is not working.
Thank you!
I don't know the correct answer but based on your solution you should be able to tidy it up:
var cards = new List<Card>();
var query = db.Cards.Where(x => x.State_ID == State_ID &&
x.Deleted != 1 &&
x.Archive != 1);
if (Sprint_ID.HasValue)
query = query.Where(x => x.Sprint_ID == Sprint_ID);
else
query = query.Where(x => x.Sprint_ID == null);
cards = query.ToList();
A nullable int won't return "null" in the way that you're thinking. You have to check the HasValue property of it to determine if there is a value, and if so then use it otherwise use null:
public PartialViewResult ListOfSingleCards( int? Sprint_ID,
int State_ID = 1)
{
var Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID.HasValue ? Sprint_ID.Value : null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
return PartialView(Cards);
}
Until something better comes a long, I'm using this:
var Cards = new List<Card>();
if (Sprint_ID == null)
{
Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == null &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
}
else
{
Cards = db.Cards.Where(x => x.State_ID == State_ID &&
x.Sprint_ID == Sprint_ID &&
x.Deleted != 1 &&
x.Archive != 1).ToList();
}

Categories