Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

help with linq select

Posted on 2014-03-05
7
Medium Priority
?
343 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 2000 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Ask an Anonymous Question!

Don't feel intimidated by what you don't know. Ask your question anonymously. It's easy! Learn more and upgrade.

Question has a verified solution.

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

Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
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…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…

636 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