Solved

help with linq select

Posted on 2014-03-05
7
337 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
Independent Software Vendors: 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

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!

Question has a verified solution.

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

A theme is a collection of property settings that allow you to define the look of pages and controls, and then apply the look consistently across pages in an application. Themes can be made up of a set of elements: skins, style sheets, images, and o…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
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…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…

749 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