Solved

help with linq select

Posted on 2014-03-05
7
336 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
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

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…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
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…
Established in 1997, Technology Architects has become one of the most reputable technology solutions companies in the country. TA have been providing businesses with cost effective state-of-the-art solutions and unparalleled service that is designed…

840 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