Solved

help with linq select

Posted on 2014-03-05
7
331 Views
Last Modified: 2016-02-10
Hello Experts,


I am having below code,

 var inv = from e in _context.Customers                        
                      select new Model.Customer
                      {
                          CustomerId = e.CustomerId,
                          CustomerName = e.CustomerName,
                          Address = e.Address,
                          contact1 = e.Contact1,
                          ContactNo2 = e.Contact2,                        
                          DateOfBirth =Convert.ToDateTime(e.DateOfBirth),
                          Anniversary = Convert.ToDateTime(e.Anniversary),
                       
                      };

Now DateOfBirth & Anniversary both fields may come as NULL values from database as they are not madatory.How can I check this?
0
Comment
Question by:johny_bravo1
  • 4
  • 3
7 Comments
 
LVL 6

Expert Comment

by:Tony O'Byrne
ID: 39906830
Working with DateTime and looking for null is tricky; a DateTime instance cannot be null.  So how do you check for null?

You can check for "reasonable" dates...  A modern anniversary is unlikely to be in the year 0001 which is what a "null" datetime will default to.

With that in mind, I wrote a simple delegate that does the trick for me in my quick tests.  Try this:

Func<DateTime, DateTime> dateValidate = (x) =>
{
    if( x.Year < 1000 ){
        return new DateTime(1900, 1, 1); //  Some default?
    }

    return Convert.ToDateTime(x);
}

Open in new window


and change your linq above to:
var inv = from e in _context.Customers                        
                      select new Model.Customer
                      {
                          CustomerId = e.CustomerId,
                          CustomerName = e.CustomerName,
                          Address = e.Address,
                          contact1 = e.Contact1,
                          ContactNo2 = e.Contact2,                        
                          DateOfBirth =dateValidate(e.DateOfBirth),
                          Anniversary = dateValidate(e.Anniversary),
                        
                      };

Open in new window


In my tests, I had the Func immediately above the linq statement - just for the sake of making things easy to play with.

Good luck!

(If you need help understanding the Func<...> ... expression, let me know; I can elaborate further if needed.

[Edit]
You can, of course, change the dateValidate Func to do something else if you need.  Hopefully the above serves as an example as to how you might "extend" your linq to validate whatever you need validated.
0
 
LVL 8

Author Comment

by:johny_bravo1
ID: 39906978
Hi Tony O'Byrne,

Thanks for the comment.

In our table BirthDate and Anniversary values are null sometimes as it is optional for the users to fill. These fields can't be set to default.

Also in class my dateofbirth and anniversary properties are of type datetime and nullable.
I get your point for DateTime not nullable but in my case I can't set any default value, so I insert null when user leave it empty.
My properties are defined like ,
public DateTime ? DateOfBirth{get;set;}

What I need is some kind of below or any better way than this,

if  (!string.isNullOrEmpty(e.DateOfBirth.ToString())
            DateOfBirth =Convert.ToDateTime(e.DateOfBirth);

Any way to do this?
0
 
LVL 6

Accepted Solution

by:
Tony O'Byrne earned 500 total points
ID: 39907049
I went back to one of my own projects - I'm fiddling with Entity Framework & Linq/SQL.  After digging around for a minute, I do see some generated code that looks like this:

public Nullable<System.DateTime> Time{ get; set; }

Open in new window


If you can, I'd suggest doing something similar.  Although the DB could store the NULL value, it'll be defaulted in the C# code unless you allow the Nullable type.

Nullables can look like:
Nullable<System.DateTime> Time1 { get; set; }
DateTime? Time2 { get; set; }  //  Note the '?'

Open in new window


Once you have that, you can then check for null directly:
if  (e.DateOfBirth != null)
            DateOfBirth =Convert.ToDateTime(e.DateOfBirth);

Open in new window


I've attached customerTest.cs - the file that I've been using to test my thoughts on this.  It builds (in a C# Console App), and when I set the breakpoint on the return statement in main(), the DateOfBirth has the expected default value set from the x==null check.

[Edit]
Actually attached the file.
customerTest.cs
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 8

Author Comment

by:johny_bravo1
ID: 39907074
Hi Thanks,

 Func<DateTime?, DateTime?> dateValidate = (x) =>
        {
            if (x == null)
            {
                //      Return some default
                return null;
            }

            return Convert.ToDateTime(x);
        };

            // && e.Address!=null
            var inv = from e in _context.Customers
                      select new Model.Customer
                      {
                          CustomerId = e.CustomerId,
                          CustomerName = e.CustomerName,
                          Address = e.Address,
                          contact1 = e.Contact1,
                          ContactNo2 = e.Contact2,

                          DateOfBirth = dateValidate(e.DateOfBirth),
                          Anniversary = dateValidate(e.Anniversary),

                      };

Now this line is showing error,
dateValidate(e.DateOfBirth) -->>cannot implicitly convert type 'System.Datetime?' to 'System.DateTime'.An explicit conversion cast
0
 
LVL 8

Author Comment

by:johny_bravo1
ID: 39907086
My bad other two properties were not declared as nullable.

Thank you very much for the quick and perfect solutions.
0
 
LVL 6

Expert Comment

by:Tony O'Byrne
ID: 39907087
The dateValidate delegate is returning a nullable type that may be confusing the Customer class.

You might need to update your Customer datastructure.  Can you change the DateOfBirth and Anniversary types to "DateTime?"  (Nullable DateTime)
0
 
LVL 6

Expert Comment

by:Tony O'Byrne
ID: 39907093
You're welcome.  Glad it worked out. :)
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
This is Part 3 in a 3-part series on Experts Exchange to discuss error handling in VBA code written for Excel. Part 1 of this series discussed basic error handling code using VBA. http://www.experts-exchange.com/videos/1478/Excel-Error-Handlin…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now