Getting MinDate instead of NULL - linq

I am calling a stored procedure, and may expect a NULL back.
However, when I get to EntityFramework with the result, it seems that the result gets converted to a Min Date (01-01-0001).
result.NextPaymentDate =
(from c in Context.GetPaymentDatesForSchedule(source.id) where c.NextPaymentFlag select c.PaymentDate)
.FirstOrDefault();
Is there a way to make it NULL, if I get a NULL value from the sproc?
It seems 'dirty' doing something like:
if (result.NextPaymentDate == DateTime.MinValue)
result.NextPaymentDate = null;

It is because the NextPaymentDate property is not nullable in your model, if you make it nullable you will then get the null value instead of min date.

Related

How to pass a null value as bind parameter

I have this table Line with a DEL_IND column. The possible values are Y or null
Im using OBIP, and there is a parameter requirement that allows selection of null or Y.
OBIP do not allow blank in their 'fixed value' menu.
I've tried to enter 'List of Values' in OBIP for No to be '' (empty string), but it doesnt seem to work.
LINE.DEL_IND = :P_DELETION_FLAG << i need to pass the value null for this clause
How do I pass null value selection into the query?
Even if you find the way to pass NULL, this:
WHERE LINE.DEL_IND = :P_DELETION_FLAG
won't work properly. If :P_DELETION_FLAG is NULL, query should look like this:
WHERE (LINE.DEL_IND = :P_DELETION_FLAG or :P_DELETION_FLAG IS NULL)
because
WHERE LINE.DEL_IND = NULL
is invalid; should be
WHERE LINE.DEL_IND IS NULL (or IS NOT NULL)

Return String instead of DateTime if LINQ Query NULL

I am using JQuery Datatables with my MVC 5 application. I am implementing sorting on one of my datatables within my MVC Controller. One of the columns displays dates to the user, and I want them to be able to sort this column, which works fine.
//Get index of column to be sorted
var sortColumnIndex = Convert.ToInt32(Request["iSortCol_0"]);
Func<survey_status, DateTime> orderingFunctionDate;
orderingFunctionDate = (c => c.InitiatedDate == null ? default(DateTime) : c.InitiatedDate.Value);
The problem is, at the moment, if c.InitiatedDate is NULL, then I return the default date 01/01/0001, otherwise I return the actual date recorded in the Database.
I don't like that I am returning 01/01/0001 to the user, it isn't great usability and could confuse them. Instead, I'd like to return something like "No date available" if c.InitiatedDate is NULL.
The problem is I can't replace
orderingFunctionDate = (c => c.InitiatedDate == null ? default(DateTime) : c.InitiatedDate.Value);
with
orderingFunctionDate = (c => c.InitiatedDate == null ? "No date available" : c.InitiatedDate.Value);
because the Function Func<survey_status, DateTime> orderingFunctionDate is returning a DateTime, not string and in making this change I get an error no implicit conversion between string and DateTime.
Can anyone help me out with this?
Any help would be greatly appreciated.
Thanks.
You should use a nullabel DateTime and return null instead of a default date. Change your function prototype to:
Func<survey_status, DateTime?> orderingFunctionDate;
And the content to:
orderingFunctionDate = (c => c.InitiatedDate);
Then I believe in jQuery DataTables you can specify a value to use when data is null.

Linq DateTime comparison not working

I have the following code:
DateTime timeStamp = Convert.ToDateTime(Request.QueryString["TimeStamp"]);
var result = (from rs in db.VRec
where
rs.TimeStamp == timeStamp &&
rs.Fixure == wFixture
select rs).ToList();
The result shows 0 even though the correct timeStamp is passed.
If I remove the part where I do the TimeStamp comparison:
rs.TimeStamp == timeStamp
The code works fine.
Any idea on why the datetime comparison may not be working?
DateTime has a pretty fine resolution - likely you are comparing timestamps that only differ in milliseconds, which will fail. You probably want something like:
DateTime now = DateTime.Now;
DateTime then = now.Add(TimeSpan.FromMilliseconds(1));
const int EPSILON_MS = 10;
if(now.Subtract(then).TotalMilliseconds < EPSILON_MS)
{
Console.WriteLine("More or less equal!");
}
Linq converts DateTime arguments to DateTime2 in the sql query executed.
That is, when you do the comparison the actual sql executed will compare a DateTime to a DateTime2. This comparison will "cast" the DateTime to a DateTime2 and the millisecond part will be expanded to a greater resolution (in an odd way in my opinion, please enlighten me).
Try to execute the following sql:
declare #d1 datetime = '2016-08-24 06:53:01.383'
declare #d2 datetime2 = '2016-08-24 06:53:01.383'
declare #d3 datetime2 = #d1
select #d1 as 'd1', #d2 'd2', #d3 'converted'
select (case when (#d1 = #d2) then 'True' else 'False' end) as 'Equal',
(case when (#d1 > #d2) then 'True' else 'False' end) as 'd1 greatest'
From the question, I do not know if you want to compare the date with time or only the date part. If you only want to compare date then following would work
var result = (from rs in db.VRec
where
rs.TimeStamp.Date == timeStamp.Date &&
rs.Fixure == wFixture
select rs).ToList();
Since you are using some reference to db, it gives me a feeling that you are fetching your records from database (which ORM you are using is not obvious from the question or tags). Assuming that you are using Entity framework the above query will fail with exception that .Date has no direct translation to sql. If so you can rewrite the query as following to make it work.
var result = (from rs in db.VRec
where
rs.TimeStamp.Day == timeStamp.Day &&
rs.TimeStamp.Month == timeStamp.Month &&
rs.TimeStamp.Year == timeStamp.Year &&
rs.Fixure == wFixture
select rs).ToList();
The benefit of this approach is that you can compare properties to arbitrary deep level i.e you can compare Hours, Minutes,Seconds etc. in your query. The second query is tested in Entity framework 5.

LINQ: Nullable object must have a value.

Let me preface this by saying I'm a novice with LINQ, and that this is code that I didn't originally write but am trying to fix. I've done a lot of research on this error, but I haven't found anything helpful yet. In fact, this error sort of makes my head spin. Anyway...
I have a LINQ query that is selecting some data from three SharePoint lists. Here it is:
private void loadPEGrid(int id)
{
dc = new SpEntityDataContext(SPContext.GetContext(this.Context).Web.Url);
EntityList<ProductDocumentMapItem> dMaps = dc.GetList<ProductDocumentMapItem>("Product Document Map");
object mappedItems = null;
mappedItems = from m in dMaps
join p in dc.PEProducts on m.ProductID.Value equals p.Id.Value
join d in dc.ProductDocuments on m.DocID.Value equals d.Id.Value
where m.ProductID.Value == id && m.ProductType == "PE"
select new {
p.Grade,
d.Path,
d.DocumentType,
d.Title,
d.Name,
Language = d.Language.Title,
m.Id,
DocId = m.DocID };
GridViewProducts.KeyFieldName = "Id";
GridViewProducts.DataSource = mappedItems;
GridViewProducts.DataBind();
}
The following fields are nullable:
m.ProductID
m.DocID
d.DocumentType
m.Id
When I debug, none of this throws an error, but when the page loads it does:
System.InvalidOperationException: Nullable object must have a value
Does this mean that one of the fields I'm selecting is null, or one of the join fields? Having checked the data, I don't think this is the case. Let me know if you need any more info from me.
System.InvalidOperationException: Nullable object must have a value
This exception is thrown when you are trying to get Value property of nullable type. So, that means one or more of following is true:
At least one of objects in dMaps has property ProductID equal to null
At least one of objects in dMaps has property DocID equal to null
At least one of objects in dc.PEProducts has property Id equal to null
At least one of objects in dc.ProductDocuments has property Id equal to null
Exception raised not by query

LINQ query - null date

Ive a simple linq query to return records with a null date field,
just want to check the synatx of the "where" line is ok
var query2 = from cs in db.tblCases
where cs.date_closed == null
etc, etc,
thanks again
DD
I would be careful with using null, I have seen issues with linq not generating the correct sytnax (ex IS NULL vs ==null)
I would recommend
var query2 = from cs in db.tblCases where !cs.date_closed.HasValue etc, etc,
Assuming your date_closed property is of a nullable type, e.g. Nullable<DateTime> aka DateTime?, that should be fine.

Resources