I was checking null like below for modifiedDate, it was working fine in 4.5 but as soon as my code deployed in C# 4.0 it is not working. What is the best way of handling below condition in 4.0 ?
modifiedDate = b?.last_modified?[0] ?? DateTime.Now,
var searchedDataList = objJson.response.docs.Select(b =>
new finalOutput
{
modifiedDate = b?.last_modified?[0] ?? DateTime.Now,
Size = b.stream_size[0]
}).ToList<finalOutput>();
public Nullable<DateTime> modifiedDate { get; set; }
I tried modifying like this but it does not work -
modifiedDate = b.last_modified[0] ?? DateTime.Now
I resolved using below -
modifiedDate = b!= null && b.last_modified != null &&
b.last_modified[0] != null ? b.last_modified[0].Value : DateTime.Now
Related
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
Here i am using simple list and one of the ageto string column is null
I am check in linq query if value not found then to return null. But value cannot be null error is coming up
var list = new[]
{
new { AgeFrom = "0", AgeTo="24"},
new { AgeFrom = "70", AgeTo= (string)null}
}.ToList();
var result = from r in list
select new EmployeeDTO
{
//AgeFrom Column is int? in DTO
AgeFrom = Convert.ToInt32(r.AgeFrom),
//AgeTo Column is int? in DTO
AgeTo = Convert.ToInt32(r.AgeTo ?? null)
}
Try this:
AgeTo = String.IsNullOrEmpty(r.AgeTo) ? (int?)null : (int?)Convert.ToInt32(r.AgeTo);
Which makes your code:
var list = new[]
{
new { AgeFrom = "0", AgeTo="24"},
new { AgeFrom = "70", AgeTo= (string)null}
}.ToList();
var result = from r in list
select new EmployeeDTO
{
//AgeFrom Column is int? in DTO
AgeFrom = Convert.ToInt32(r.AgeFrom),
//AgeTo Column is int? in DTO
String.IsNullOrEmpty(r.AgeTo) ? (int?)null : (int?)Convert.ToInt32(r.AgeTo)
};
Convert.ToInt32 can not convert null to an integer, that will always throw an exception.
One option would be to change:
AgeTo = Convert.ToInt32(r.AgeTo ?? null)
to:
AgeTo = r.AgeTo != null ? Convert.ToInt32(r.AgeTo) : null
The statement r.AgeTo ?? null is an example of the null-coalescing operator, which, in your case, is essentially saying that if r.AgeTo is null, then use null instead. As this isn't what you were trying to achieve, you are in fact passing null into Convert.ToInt32, which is causing your error.
I am writing LINQ query to return null if it does not have any value (null in database) but return 0 or proper number if it has 0 or proper number in database.
I have following my model class
public class Test
{
public decimal? TotalHours { get; set; }
}
The following is LINQ selection query. This line assign null to TotalHours successfully. I am fine till here.
List<Test> Item = parentQuery
.Select(x => new Test
{
TotalHours Hours = (decimal?) x.TotalMinutes != null ? (decimal?) x.TotalMinutes : (decimal?)null,
}).ToList();
My further group by query assign 0 if TotalHours is null whereas i am expecting it be assigned/remained as null.
List<Test> ItemList = Item.GroupBy(x => x.Id)
.Select(x => new Test
{
TotalHours = x.Sum(y => (decimal?)y.TotalHours)
}).ToList();
How i can return null to my view? kindly dont advise Data Annotation way.
thanks
One way of doing this would be testing for presence of non-null values explicitly:
List<Test> ItemList = Item.GroupBy(x => x.Id)
.Select(x => new Test {
TotalHours = x.Any(y => y.TotalHours.HasValue) ? x.Sum(y => (decimal?)y.TotalHours) : null
}
).ToList();
The check with Any(...) verifies that the group has at least one non-null item before using Sum. If all items are null, the expression produces null result.
//Below mentioned class is created to understand the problem, while this is created through Linq2Sql.
public class JobAds
{
public int ID { get; set; }
public int EmployerRef { get; set;}
}
int? employerId = null;
var jobAdListing = JobAds.Where
( n => (!employerId.HasValue || n.EmployerRef == employerId.Value )).ToList();
The Issue is I'm getting "Nullable object must have a value." at the above line. After doing some debugging, I feel n.EmployerRef == employerId.Value is making some trouble, but unable to find anything good.
Just write liks this, you don't have to worry about the null values (since NULL == NULL equals false)
int? employerId = null;
var jobAdListing = tblCompanies.Where
(n => (n.fkUserID_responsible == employerId)).ToList();
Or you can keep your code and just remove the ".value"
var jobAdListing = JobAds.Where
( n => (!employerId.HasValue || n.EmployerRef == employerId)).ToList();
in my local playground a simmilar case works with this easiest approach:
using (UnitOfWork.Begin("LinqToSql"))
{
Guid? id1 = null;
Guid? id2 = this.personRepository.GetAll().First().FavouriteProjectId;
var all = this.personRepository.GetAll().Where(o => o.FavouriteProjectId == id1 || o.FavouriteProjectId == id2).ToArray();
}
for you, this should work too:
int? employerId = null;
int? employerType = null; /* OTHER Conditions */
var list = JobAds.Where(n => n.EmployerRef == employerId &&
n.EmployerTypeRef == employerType)).ToArray();
Here is the code snippet, actually the whole method. This method works f,ine when NULLAblE Foreign Key Refernces has value. When the value is not there, then this method does not work. My idea is to get all the records even if the references column is NULL. Here is the code :
public List<PostedJob> GetPostedJobs(int startingIndex, int maximumRows)
{
using (var records = new CommonEvent())
{
var resultSet =
from r in records.ProjectPosts
join rr in records.Categories on r.Category_FK equals rr.ID
join al in records.ApplyForLimits on r.ApplyForLimit_FK
equals al.Id
//from uImage in
// records.UploadedFiles
// .Where(uu=>uu.Id == r.UploadedFileInfo_FK
// || r.UploadedFileInfo_FK == null).DefaultIfEmpty()
join a in records.UploadedFiles on r.UploadedFileInfo_FK
equals a.Id into something
from uImage in something.DefaultIfEmpty()
orderby r.PostId
select new Models.PostedJob
{
ApplyForLimitName = al.Name,
ProjectTitle = r.ProjectTitle,
ProjectDescription = r.ProjectDescription,
ProjectSummaryDescription = r.ProjectSummaryDescription,
SkillsRequirements = r.SkillsRequirements,
CategoryName = rr.CategoryName,
UploadedFileID = (int) r.UploadedFileInfo_FK,
UploadedFileInformation = uImage == null ?
new Models.UploadedFile
{
fileContents = new byte [] { (byte) 0},
FileExtension = string.Empty,
FileName = string.Empty,
FileSize = 0,
UploadedDate = DateTime.Now
}
:
new Models.UploadedFile
{
fileContents = uImage.FileContents,
FileExtension = uImage.FileExtension,
FileName = uImage.FileName,
FileSize = uImage.FileSize,
UploadedDate = DateTime.Now
}
};
return resultSet.Skip(startingIndex).Take(maximumRows).ToList();
}
Thank you for any suggestions or ideas on how to proceed . I am using .NET 4.0
Can you not use the Associations generated for you?
var a = records
.ProjectPosts
.Select(
projectPost =>
new Models.PostedJob()
{
ProjectTitle = projectPost.ProjectTitle,
CategoryName = projectPost.Category.CategoryName,
});
Something along those lines?
EDIT: And just add Null checks when the FK may fail
example:
CategoryName = projectPost.Category == null ? String.Empty : projectPost.Category.CategoryName,