.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Linq to SQL returns null for DateTime fields.

Posted By:      Posted Date: August 24, 2010    Points: 0   Category :ASP.Net

I have a linq to sql entity class in which I declared some DateTime fileds like this:

[Column(DbType = "smalldatetime")]
public DateTime? StartDate { get; set; }

And this is how I fetch data form repository:

return repository.Logs.OrderByDescending(l => l.LogID).FirstOrDefault();

All non DateTime fields are filled properly but all datetimes are null.

[Column(DbType = "smalldatetime")]

        public DateTime? StartDate { get; set; }

View Complete Post

More Related Resource Links

LINQ with GridView and edit fields


My project includes a grid view which displays information of inventory items (Assets), data is quried from AssetTable. The GridView has a command field to allow editing, below is a description of the tables and how data is displayed


BuildingTable: (BuildingID, BuildingName)

AssetTable: (BuildingID,..,....,....)


ItemTemplate: Using a LINQ query I join the two table and displays in a label control a string which includes BuildingID and BuildingName (5 North Building)

 EditItemTemplate: Using a LINQ query I populate a DropDownList with strings of BuildingID and BuildingName same as above.
Here  issue which I need to resolve:
1.  ItemTemplate display the correct information (BuildingID BuildingName) but when I switch to EditItemTemplate the pair that is 
displayed is the first one on the list, how do I make is scroll to the item which was displayed in the label ?
<asp:CommandField ShowEditButton="True" >
                    <ControlStyle Wi

linq and max, if return null return error


hi there
i have this query :

var result2 = (from TH in DB.Threshold
                          where TH.ProductSKUID == int.Parse(HID_ProductSKUID.Value)
                          select TH.ThresholdID).Max();

the problem is that if this query does not find any items, return null, so thow exception
how can i do to return 0??

Linq join fields for return data


  how would I join fields together?

           return (from c in storedb.Product_Categories

                         where c.Category_Name.Contains(searchText)
                         orderby c.Category_Name
                         select new {
                                    c.Category_Key && " ;" && c.Category_Name // HOW CAN I DO THIS.....

How to handle null while converting from my datatable to List<> using LINQ


I am converting my datatable to LISt using LINQ
how do I handle nulls coming from database

List<Port> portDetails = new List<Port>();
DataTable dt = ds.Tables[0];               
portDetails = (from q in dt.AsEnumerable()
select new Port
PortCode = q.Field<string>("Code"),
ExtCode = q.Field<string>("Nb"),
Name = q.Field<string>("Name"))

In the above query if Code is null I do not want property
portcode to be set to the value it should only set if it is
not null or not blank 
PortCode = q.Field<string>("Code"),

What should be syntax
I was trying somethign like this which doesnt work
Portcode = q.Field<bool>("Code") == null ? null : q.Field<bool>("Code")


BuildManager.GetType returns null until application pool recycles

Our application uses the Enterprise Library's PropertyProxyValidator class to validate user input (v4.1 - Oct 2008).  On occassion, the code will raise an exception saying the source type cannot be found.  This error persists until the application pools recycle at night, at which point everything works again.  It tends to only affect one of the web front ends at a time (there are two). I tracked down where the exception was being raised, and this is the section of code:Type IValidationIntegrationProxy.ValidatedType { get { if (string.IsNullOrEmpty(this.sourceTypeName)) { throw new InvalidOperationException(Resources.ExceptionNullSourceTypeName); } Type validatedType = BuildManager.GetType(this.SourceTypeName, false, false); if (validatedType == null) { throw new InvalidOperationException( string.Format(CultureInfo.CurrentUICulture, Resources.ExceptionInvalidSourceTypeName, this.sourceTypeName)); } return validatedType; } } (As you can see, the value for this.SourceTypeName is shown in the exception and I've checked that it matches exactly.) We have never been able to reproduce this exception and at this point don't have any ideas left as far as causes.  For a while, my suspicion was that it was related to the Temporary ASP.NET Files folder.  The last

error in MVC2 on empty string form fields which are required: "This property cannot be set to a null

In model I have:[DisplayName("ISBN")] [Required(ErrorMessage = "ISBN is required.")] [StringLength(50, ErrorMessage = "ISBN book must have max {1} chars.")] [DisplayFormat(ConvertEmptyStringToNull = false)] public string isbn { get; set; }But when I submit form with empty field ISBN I have an error - ConstraintException: This property cannot be set to a null value.I have find that other people have the same problem and they say that debbugger in VS2010 works wrong - yes ?http://p2p.wrox.com/book-professional-asp-net-mvc-2/79788-constraintexception-unhandled-user-code.html#post259245http://efreedom.com/Question/1-3129080/Server-Side-Validation-REQUIRED-String-Property-MVC2-Entity-Framework-Workhttp://mvcmusicstore.codeplex.com/workitem/6604

Updating a List item field value in a SPD Workflow is setting Date fields to null

Hello everybody,I faced a very weird behavior while creating a workflow in SPD against a Document Library.Here is the case:1- Create a document library in sharepoint site.2- Add a custom column of type DATE.3- Upload any document to the library4- Edit the item metadata and set the custom date field to any date you want.5- Now using sharepoint designer, create a very simple Workflow with only one action that updates the current item "Title" field to any value. (Note: In my case I set the workflow to start manually and not automatically)6- Save the workflow and then start it on the uploaded item.7- Now check the value of the date column after the workflow is finished.8- You will see that the Date field is Empty... (very weird)Notes:   1-This behavior will not appear on a standard list. it is only appearing in a Document library.  2- I am using WSS 3.0 SP2 + MOSS 2007 SP2. Also SharePoint designer 2007 SP2Did anyone face this situation and does it have a fix, or am I doing something wrong here... Please help.Regards,Maheed

Linq null value

 Hello,I am making a website to store invoices so i can mail them to clients. So i got a table for clients, invoices and one with invoice products/services. When an invoice has no products/services added to them and it returns null i get the error "the null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type."I just started with linq. Before i always used mysql. Mostly i just had to call data from 1 table so forgive me if my linq query isn't really correct.  Dim invoices = From i In db.invoices _                       Group Join p In db.products On i.id Equals p.invoiceId Into invoiceProducts = Group _                       Select New With {i.client.naam, i.titel, (From iP In invoiceProducts Select iP.prijs).Sum} So the idea is that i show the client's naam, the title of the invoice and the total amount the clients will need to pay for products and services. Kind regards Geert

Registry OpenSubKey returns null

Hi,It seemed to be the right place to post to.My problem is that when I try to read registry key, I get null value, even if it exists (regedit shows it exists).Application is windows service with Log On As Local System and registry key im trying to read is in HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSIDOn my development machine (x64 win7) it works fine. But in live server (x64 windows server 2008 r2) I get NULL. These operating systems should have similar policies or does Local System on server 2008 have any restrictions i should know about?RegardsMax

DateTime Null Or Minimum Value

Hello, I am working on a authentication system and I have the following: create table dbo.Users (   Id int identity not null,   LastLock datetime not null,   LastLogin datetime not null,   LastPasswordChange datetime not null,   LastReset datetime not null,   Username nvarchar(40) not null constraint Users_Username_U unique,     constraint Users_PK primary key clustered(Id) ) -- Users When a user opens the account there was never a login, it was never locked or password changed. So should I insert in this fields a Null value or a "SQL Minimum Date". What is your opinion in relation to this? Thanks, MiguelHello,I am working on a authentication system and I have the following:create table dbo.Users (  Id int identity not null,  LastLock datetime not null,  LastLogin datetime not null,  LastPasswordChange datetime not null,   LastReset datetime not null,  Username nvarchar(40) not null constraint Users_Username_U unique,    constraint Users_PK primary key clustered(Id)) -- UsersWhen a user opens the account there was never a login, it was never locked or password changed.So should I insert in this fields a Null value or a "SQL Minimum Date".What is your opinion in relation to this?What is the approach

FindControl returns null

I am trying to fetch two Labels within a Repeater element to attach data to; which Label is assigned which Data Field depends on the result of a Radio Button List, hence why I need to fetch them in the code behind. This is the ASP.NET code: <asp:View ID="vwSportType" runat="server"> <table> <tr> <td rowspan="2"> <span class="boldtext">Select type of sport:</span><br /><br /> <asp:ListBox ID="lbType" runat="server" AutoPostBack="true" OnSelectedIndexChanged="lbType_OnSelectedIndexChanged" Height="300px" Width="12em"> </asp:ListBox> </td> <td width="70%"> <span class="boldtext">Show by: <asp:RadioButtonList ID="rbSportType" runat="server" RepeatDirection="Horizontal"> <asp:ListItem Text="Date, Sport" Selected="True" Value="0"></asp:ListItem> <asp:ListItem Text="Sport,

how to insert null or empty string to datetime var ?

hi i get data from xml file and sometime the date is empty. i have this code:     try { TimeTo = Convert.ToDateTime(R[15].ToString()); }         catch { TimeTo = null ; } but i got error because i cant insert null to datetime var what i can do ? thak's in advance

Null values in formula fields

Hi,I tried using this and am concatenating the fields together.  It does not appear to be working.  Here's what I have.  Any suggestions?   IIF(IsNull({nomination.recparty1}), '0.0', {nomination.recparty1} ) &  chr(13)IIF(IsNull({nomination.recparty2}), '0.0', {nomination.recparty2} ) & chr(13)IIF(IsNull({nomination.recparty3}), '0.0', {nomination.recparty3} )andif IsNull({nomination.recparty1}) then '0.0' else {nomination.recparty1} & chr(13)if IsNull({nomination.recparty2}) then '0.0' else {nomination.recparty2} & chr(13)if IsNull({nomination.recparty3}) then '0.0' else {nomination.recparty3}Both this gets failed beacuse my fields are returned as null.Please get me to solve this.Thanks in advance.Regards,Mugil

Why this returns null

hi friends, i have a table AppUser.UsersUserRole that has the following structure: idx auto ur_id int -- user role id id int    -- user id that has the following data:  From Drop Box  when i ran query to returns a csv: declare @csv nvarchar(max) select @csv = @csv + coalesce( convert(nvarchar(max), ur_id) + ',','' ) from AppUser.UsersUserRoles where id = 28 select @csv it returns:  From Drop Box  but there are three records for 28, why it displays null, how do i fix this? thanks

SCOPE_IDENTITY() returns null after paramerized INSERT


I have a very simple database, without any triggers at this point. One of my tbales has a auto increment key (IDENTITY field). As the record has a string attribute, which valeu is received from the user, I insert a new records with a parametized INSERT statement. After insertion I try to fetch the new record's ID with the sttament SELECT SCOPE_IDENTITY(), but ti return null - while SELECT @IDENTITY and SELECT IDENT_CURRENT returns the valid values.

Moreover, if - for testing purposes - I execute the same insert without parameters, (i.e. providing the string value directly in the INSERT statement), then even SCOPE_IDENTITY() returns the correct value.

I didn't find any reference in the documentation regarding such restriction. Is is a known bug or the result of some misunderstading?

Downloading a document from a sharepoint site to local file system, copy web service returns null

Hi Guys,
               I am trying to get this done for the last 2 days and I am still banging my head to the wall.
All I need to do is to download files from my sharepoint site library that uses integrated windows authentication. I was using copy webservice : getItem method to accomplish this.

CopyService.GetItem(copySource, out myFieldInfoArray, out myByteArray);

Problem : myByteArray is always returned as NULL

Note: I have tried the same with another site that uses forms authentication but the result was the same (NULL !!)

This is my code:


Copy copy = new CopyService.Copy();


Datetime fields within a fact table


Morning all,

I'm currently defining a fact table in my first datacube and have a question (basic one albeit).  Can a datetime column be left in a fact table as a measure or should this be stored only within a dimension table?  The other columns I have left in thus far are foreign keys for the dimension tables.

Any pointers appreciated.


ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend