Nullable date with Linq and Model class in C#

In C# Model class you may have experienced a nullable Error while fetching the rows with nullable column from database to your Model objects.

To treat the nullable in proper way , you have to tell your Model class and Linq this is nullable field.

Model class

*The nullable is applied to Value Type .This is not required for string

In the Model class I have a field edate which is in database is a nullable field. I want to make this field nullable in my model

 class StocKBatchModel
        public int B_Id { get; set; }        
        public string Name { get; set; }
        public DateTime? Edate { get; set; }

By placing ? after the type of my class property , it becomes nullable. Say the DateTime becomes nullable , I can use the same in Linq in my LInq query as follows

var blist = (from m in batch_table.AsEnumerable()                                 
                                 select new
                                     obj = new Models.StocKBatchModel()
                                         B_Id = m.Field<int>("b_id"),
                                         Name = m.Field<string>("name"),
                                         Edate = m.Field<DateTime?>("exp_date"),                                       

Hope this will helpful for someone.

Published by


A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.