linq - condtionally hide a property in a .select() statement - linq

[frangment of a linq query]
query.Select(c => new OdsSummaryResponse
{
Id = c.RISODS_Id,
Driver = c.CDGOREC.Where(a => a.CDGOREC_Conducente).FirstOrDefault().PERSONALE.PERSONE.PERSONE_CognomeNome,
Operators = c.CDGOREC.Where(a => myexternavar == true && !a.CDGOREC_Conducente && a.CDGOREC_PersonaleId != null).Select( d => new Operatori() {
Id = (int)d.CDGOREC_PersonaleId,
Nominativo = d.PERSONALE.PERSONE.PERSONE_CognomeNome,
Codice = d.PERSONALE.PERSONALE_Codice
}).ToList()
}).OrderByDescending(c => Id);
in the subquery Operators = c.CDGOREC.Where when an external variable myexternavar=false i'd like to completely hide the property "Operators" from the output.
But this code shows me an empty array,
{
"Id": 194214,
"Driver": "XXXXXXXX",
"OperatorsNo": 1,
"Operators": [] //i'd like to hide this property if myexternavar=false
}
is it possible to exclude the property at all???

You can use Conditional Property Serialization to instruct the Serializer when to include that property.
For example, the following will not emit the Operators property when it's either null or empty:
public class OdsSummaryResponse
{
// ...
public IList<Operatori> Operators { get; set;}
public bool ShouldSerializeOperators()
{
return this.Operators?.Count > 0;
}
}

Related

How to test null value on nullable enum

I have documents with property _report_type, it supposed to contain a string "FTE", or "CAB".
In legacy document, it can be null or not exist at all (undefined), they are supposed to be "ContractorWorkReport".
My mapping:
public class Order : Document, IBaseEntity<string>
{
[JsonProperty(Order = 70, PropertyName = "orderData")]
public OrderData Data { get; set; }
}
public class OrderData
{
[JsonProperty(Order = 60, PropertyName = "_order_type")]
public OrderType? OrderType { get; set; }
}
[JsonConverter(typeof(StringEnumConverter))]
public enum OrderType
{
[EnumMember(Value = "TFE")]
ContractorWorkReport,
[EnumMember(Value = "CAB")]
BudgetElectricMeter
}
My query based on that :
var query = _client.CreateDocumentQuery<T>($"/dbs/{_databaseId}/colls/{CollectionId}");
if (filter.OrderType.Value == OrderType.ContractorWorkReport)
query = query.Where(o => o.Data.OrderType == null || !o.Data.OrderType.HasValue || o.Data.OrderType == filter.OrderType);
else
query = query.Where(o => o.Data.OrderType == filter.OrderType);
This query crashes because of the o.Data.OrderType == null, error message is :
Unable to cast object of type 'Microsoft.Azure.Documents.Sql.SqlNullLiteral' to type 'Microsoft.Azure.Documents.Sql.SqlNumberLiteral'.'
How can fix this? Right now, i do this, but it's dirty...
if (filter.OrderType.Value == OrderType.ContractorWorkReport)
query = query.Where(o => o.Data.OrderType != OrderType.BudgetElectricMeter);
else
query = query.Where(o => o.Data.OrderType == filter.OrderType);
Thanks!
First, I would recommend you use this for the first parameter in CreateDocumentQuery : UriFactory.CreateDocumentCollectionUri(databaseId, collectionId)
To answer your question, you are comparing an int to a null. o.Data.OrderType, being an enum, resolves to an int. You may want to compare that to the default enum value 0 or query over documents where o.Data.OrderType is not a key at all

enumerable group field using Linq?

I've written a Linq sentence like this:
var fs = list
.GroupBy(i =>
new {
X = i.X,
Ps = i.Properties.Where(p => p.Key.Equals("m")) <<<<<<<<<<<
}
)
.Select(g => g.Key });
Am I able to group by IEnumerable.Where(...) fields?
The grouping won't work here.
When grouping, the runtime will try to compare group keys in order to produce proper groups. However, since in the group key you use a property (Ps) which is a distinct IEnumerable<T> for each item in list (the comparison is made on reference equality not on sequence equality) this will result in a different collection for each element; in other words if you'll have two items:
var a = new { X = 1, Properties = new[] { "m" } };
var b = new { X = 1, Properties = new[] { "m" } };
The GroupBy clause will give you two distinct keys as you can see from the image below.
If your intent is to just project the items into the structure of the GroupBy key then you don't need the grouping; the query below should give the same result:
var fs = list.Select(item => new
{
item.X,
Ps = item.Properties.Where(p => p.Key == "m")
});
However, if you do require the results to be distinct, you'll need to create a separate class for your result and implement a separate IEqualityComparer<T> to be used with Distinct clause:
public class Result
{
public int X { get; set; }
public IEnumerable<string> Ps { get; set; }
}
public class ResultComparer : IEqualityComparer<Result>
{
public bool Equals(Result a, Result b)
{
return a.X == b.X && a.Ps.SequenceEqual(b.Ps);
}
// Implement GetHashCode
}
Having the above you can use Distinct on the first query to get distinct results:
var fs = list.Select(item => new Result
{
X = item.X,
Ps = item.Properties.Where( p => p.Key == "m")
}).Distinct(new ResultComparer());

How to Search through all fields in a LINQ table?

in LINQ how do i search all fields in a table, what do i put for ANYFIELD in the below?
Thanks
var tblequipments = from d in db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).Include(t => t.AssetType)
where d."ANYFIELD" == "VALUE" select d;
You can't. You must compare each field individually. It doesn't make sense to compare all fields, given a field may not even be of the same type as the object you're comparing to.
You can, using reflection. Try this:
static bool CheckAllFields<TInput, TValue>(TInput input, TValue value, bool alsoCheckProperties)
{
Type t = typeof(TInput);
foreach (FieldInfo info in t.GetFields().Where(x => x.FieldType == typeof(TValue)))
{
if (!info.GetValue(input).Equals(value))
{
return false;
}
}
if (alsoCheckProperties)
{
foreach (PropertyInfo info in t.GetProperties().Where(x => x.PropertyType == typeof(TValue)))
{
if (!info.GetValue(input, null).Equals(value))
{
return false;
}
}
}
return true;
}
And your LINQ query:
var tblequipments = from d in db.tblEquipments.Include(t => t.User).Include(t => t.ChangeLog).Include(t => t.AssetType)
where CheckAllFields(d, "VALUE", true) select d;
The third parameter should be true if you want to check all fields and all properties, and false if you want to check only all fields.
EDIT: Someone already built this...see here.
Not a full answer, but I don't agree with assertion that you simply can't...
You could come up with an extension method that dynamically filtered the IQueryable/IEnumerable (I'm guessing IQueryable by the db variable) based on properties of a similar type for you. Here's something whipped up in Linqpad. It references PredicateBuilder and is by no means complete/fully accurate, but I tested it out in Linq-to-SQL on some of my tables and it worked as described.
void Main()
{
YourDbSet.WhereAllPropertiesOfSimilarTypeAreEqual("A String")
.Count()
.Dump();
}
public static class EntityHelperMethods
{
public static IQueryable<TEntity> WhereAllPropertiesOfSimilarTypeAreEqual<TEntity, TProperty>(this IQueryable<TEntity> query, TProperty value)
{
var param = Expression.Parameter(typeof(TEntity));
var predicate = PredicateBuilder.True<TEntity>();
foreach (var fieldName in GetEntityFieldsToCompareTo<TEntity, TProperty>())
{
var predicateToAdd = Expression.Lambda<Func<TEntity, bool>>(
Expression.Equal(
Expression.PropertyOrField(param, fieldName),
Expression.Constant(value)), param);
predicate = predicate.And(predicateToAdd);
}
return query.Where(predicate);
}
// TODO: You'll need to find out what fields are actually ones you would want to compare on.
// This might involve stripping out properties marked with [NotMapped] attributes, for
// for example.
private static IEnumerable<string> GetEntityFieldsToCompareTo<TEntity, TProperty>()
{
Type entityType = typeof(TEntity);
Type propertyType = typeof(TProperty);
var fields = entityType.GetFields()
.Where (f => f.FieldType == propertyType)
.Select (f => f.Name);
var properties = entityType.GetProperties()
.Where (p => p.PropertyType == propertyType)
.Select (p => p.Name);
return fields.Concat(properties);
}
}
Useful resources for the unresolved part:
Finding the relevant properties
if this help some one.
first find all properties within Customer class with same type as query:
var stringProperties = typeof(Customer).GetProperties().Where(prop =>
prop.PropertyType == query.GetType());
then find all customers from context that has at least one property with value equal to query:
context.Customer.Where(customer =>
stringProperties.Any(prop =>
prop.GetValue(customer, null) == query));

having troubles getting !any() query to work with raven db

I am new to RavenDB and it's been frustrating try to get the Any() LINQ query to work correctly. Here is what my document looks like:
{
"Key": "BKey",
"Text": "B Key",
"IsLocal": false,
"Category": null,
"_destroy": false,
"Translations": [
{
"CultureCode": "es-ES",
"Text": null
},
{
"CultureCode": "ja-JP",
"Text": "Hello"
}
]
}
I would expect the following query to give me all entries that don't have translations for "es-ES":
var nonTranslatedEntries =
_docs.Query<ResourceEntry>().Where( e => e.Translations == null || e.Translations.Count == 0 || !e.Translations.Any(t => t.CultureCode == "es-ES" && t.Text != null))
However, this isn't working. It's bringing back the entries even when a translation for the specified CultureCode exists. It works if I have only have one item inside the translations array. But as soon as I have more than one item inside the translations array, then the query stops working.
As an alternative solution, I tried to do the following:
var translatedEntries = from re in _docs.Query<ResourceEntry>()
where re.Translations.Any(t => t.CultureCode == cultureCode && t.Text != null)
select new {Id = re.Id};
var translatedIds = translatedEntries.ToList().Select(e => e.Id).ToList();
var nonTranslatedEntries =
_docs.Query<ResourceEntry>().Where(e => !e.Id.In(translatedEntryIds));
But that just brings back an empty list.
Any help would be very much appreciated.
Thanks,
Nizar
A static index that will get the job done:
public class Resources_ByTranslation :
AbstractIndexCreationTask<ResourceEntry, Resources_ByTranslation.IndexEntry>
{
public class IndexEntry
{
public string Key { get; set; }
public string CultureCodes { get; set; }
}
public Resources_ByTranslation()
{
Map = entries => from entry in entries
select new {
entry.Key,
CultureCodes = entry.Translations
.Where(x => x.Text != null)
.Select(x => x.CultureCode)
};
}
}
Then query with:
var nonTranslatedEntries =
session.Query<Resources_ByTranslation.IndexEntry, Resources_ByTranslation>()
.Where(x => x.CultureCodes != "es-ES")
.As<ResourceEntry>();
Note that the CultureCodes list is being treated as single string. This is due to how then index matching works internally. It's slightly strange, but it does work.
I ended up fixing my issue as follows:
Upon creation of a resource entry, I go ahead and create all the possible translations and set the translation text to null:
{
"Key": "BKey",
"Text": "B Key",
"IsLocal": false,
"Category": null,
"_destroy": false,
"Translations": [
{
"CultureCode": "es-ES",
"Text": null
},
{
"CultureCode": "ja-JP",
"Text": null
}
]
}
I then created the following index:
public class ResourceEntries_ByCultureCodes : AbstractIndexCreationTask<ResourceEntry>
{
public ResourceEntries_ByCultureCodes()
{
Map = entries => from e in entries
select new
{
e.Id,
e.Key,
e.Text,
e.IsLocal,
e.Category,
_ = e.Translations.Select(t => CreateField(t.CultureCode, t.Text != null, false, true))
};
}
}
That gives me a flat record of translations with the value set to 'true' if a translation exists for a that specific culture. For example, I get back something like this:
{
Id,
Key,
Text,
IsLocal,
Category,
es-ES: <true> or <false> depending upon whether Translation.Text != null
ja-JP:<true> or <false> depending upon whether Translation.Text != null
}
I can then do LuceneQuery as follows to get all entries for "es-ES" that have NOT been translated:
_docs.LuceneQuery<ResourceEntry, ResourceEntries_ByCultureCodes>().WhereEquals("es-ES", false);
I wish there were an easier solution, though.

The method 'OrderBy' must be called before the method 'Skip' Exception

I was trying to implement the jQgrid using MvcjQgrid and i got this exception.
System.NotSupportedException was unhandled by user code
Message=The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.
Though OrdeyBy is used before Skip method why it is generating the exception? How can it be solved?
I encountered the exception in the controller:
public ActionResult GridDataBasic(GridSettings gridSettings)
{
var jobdescription = sm.GetJobDescription(gridSettings);
var totalJobDescription = sm.CountJobDescription(gridSettings);
var jsonData = new
{
total = totalJobDescription / gridSettings.PageSize + 1,
page = gridSettings.PageIndex,
records = totalJobDescription,
rows = (
from j in jobdescription
select new
{
id = j.JobDescriptionID,
cell = new[]
{
j.JobDescriptionID.ToString(),
j.JobTitle,
j.JobType.JobTypeName,
j.JobPriority.JobPriorityName,
j.JobType.Rate.ToString(),
j.CreationDate.ToShortDateString(),
j.JobDeadline.ToShortDateString(),
}
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
GetJobDescription Method and CountJobDescription Method
public int CountJobDescription(GridSettings gridSettings)
{
var jobdescription = _dataContext.JobDescriptions.AsQueryable();
if (gridSettings.IsSearch)
{
jobdescription = gridSettings.Where.rules.Aggregate(jobdescription, FilterJobDescription);
}
return jobdescription.Count();
}
public IQueryable<JobDescription> GetJobDescription(GridSettings gridSettings)
{
var jobdescription = orderJobDescription(_dataContext.JobDescriptions.AsQueryable(), gridSettings.SortColumn, gridSettings.SortOrder);
if (gridSettings.IsSearch)
{
jobdescription = gridSettings.Where.rules.Aggregate(jobdescription, FilterJobDescription);
}
return jobdescription.Skip((gridSettings.PageIndex - 1) * gridSettings.PageSize).Take(gridSettings.PageSize);
}
And Finally FilterJobDescription and OrderJobDescription
private static IQueryable<JobDescription> FilterJobDescription(IQueryable<JobDescription> jobdescriptions, Rule rule)
{
if (rule.field == "JobDescriptionID")
{
int result;
if (!int.TryParse(rule.data, out result))
return jobdescriptions;
return jobdescriptions.Where(j => j.JobDescriptionID == Convert.ToInt32(rule.data));
}
// Similar Statements
return jobdescriptions;
}
private IQueryable<JobDescription> orderJobDescription(IQueryable<JobDescription> jobdescriptions, string sortColumn, string sortOrder)
{
if (sortColumn == "JobDescriptionID")
return (sortOrder == "desc") ? jobdescriptions.OrderByDescending(j => j.JobDescriptionID) : jobdescriptions.OrderBy(j => j.JobDescriptionID);
return jobdescriptions;
}
The exception means that you always need a sorted input if you apply Skip, also in the case that the user doesn't click on a column to sort by. I could imagine that no sort column is specified when you open the grid view for the first time before the user can even click on a column header. To catch this case I would suggest to define some default sorting that you want when no other sorting criterion is given, for example:
switch (sortColumn)
{
case "JobDescriptionID":
return (sortOrder == "desc")
? jobdescriptions.OrderByDescending(j => j.JobDescriptionID)
: jobdescriptions.OrderBy(j => j.JobDescriptionID);
case "JobDescriptionTitle":
return (sortOrder == "desc")
? jobdescriptions.OrderByDescending(j => j.JobDescriptionTitle)
: jobdescriptions.OrderBy(j => j.JobDescriptionTitle);
// etc.
default:
return jobdescriptions.OrderBy(j => j.JobDescriptionID);
}
Edit
About your follow-up problems according to your comment: You cannot use ToString() in a LINQ to Entities query. And the next problem would be that you cannot create a string array in a query. I would suggest to load the data from the DB with their native types and then convert afterwards to strings (and to the string array) in memory:
rows = (from j in jobdescription
select new
{
JobDescriptionID = j.JobDescriptionID,
JobTitle = j.JobTitle,
JobTypeName = j.JobType.JobTypeName,
JobPriorityName = j.JobPriority.JobPriorityName,
Rate = j.JobType.Rate,
CreationDate = j.CreationDate,
JobDeadline = j.JobDeadline
})
.AsEnumerable() // DB query runs here, the rest is in memory
.Select(a => new
{
id = a.JobDescriptionID,
cell = new[]
{
a.JobDescriptionID.ToString(),
a.JobTitle,
a.JobTypeName,
a.JobPriorityName,
a.Rate.ToString(),
a.CreationDate.ToShortDateString(),
a.JobDeadline.ToShortDateString()
}
})
.ToArray()
I had the same type of problem after sorting using some code from Adam Anderson that accepted a generic sort string in OrderBy.
After getting this excpetion, i did lots of research and found that very clever fix:
var query = SelectOrders(companyNo, sortExpression);
return Queryable.Skip(query, iStartRow).Take(iPageSize).ToList();
Hope that helps !
SP

Resources