Solved

help with linq select

Posted on 2014-03-05
7
332 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Icons and Colors for Terms 3 24
Runtime Exceptions when trying to submit data 28 37
Error in script 11 47
Finally almost got it 5 16
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 article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
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…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

920 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

14 Experts available now in Live!

Get 1:1 Help Now