Linq Grouping By Nullable Datetime And Using This As Criteria?

Nov 17, 2009

I am struggling with a nullable datetime column [DateInsp] in an ASP.NET app which uses SubSonic3, Linq, MS SQL Server 2005.I had this all working when the datetime column [DateInsp] did not allow nulls. A new requirement forced me to set the [DateInsp] column to allow nulls and now I am struggling getting this piece of functionality to work properly again.

Problem 1:I need to first render a dropdown list of the 7 most recent inspection dates for a given inspector (this is a grouped list of the 7 most recent dates for the inspector). Here is the TSQL that I need to convert to Linq syntax:

declare @InspectorID varchar(5)
set @InspectorID = 'GPA'
select top 7 convert(nvarchar(30), [DateInsp], 101) InspectedDate

[code]....

If I can't get this work properly using Linq, BUT I can/could build a stored proc to return the list of dates and throw that into a dropdown. Fair enough. I've been fighting with the Linq syntax?

Problem 2: I need to use the selected date in the dropdown mentioned above to pull the correct records for this inspector and the correct date. Again, this is a nullable datetime field and this is real sticking point for me.

Here was the original Linq syntax that accomplished the requirement before I had to change the datetime field to allow Nulls:

Dim query = (From i In db.IncomingInspections _
Where i.InspectorID = User.Identity.Name _
Group By Key = New With {i.DateInsp} Into Group _

[code]....

For some reason I can't use the .Value property; I get: The member 'Value' is not supported I get: "Incorrect syntax near '<'." if I try to add the date comparison to the where clause too.

View 2 Replies


ADVERTISEMENT

C# - Comparing The Nullable DateTime's?

Nov 17, 2010

I am a c#/asp.net developer and I am having to work on a VB/asp.net. I have two variables

Dim originalDate as DateTime?
Dim newDate as DateTime?

Both nullable datetimes, originalDate is a nullable date I am getting from the database and newDate time is set in code, I need to compare them, they can either both have dates, neither have dates or one have and one not.

I have a bit of code as follows:

if origEndDate = origEndDate then

When both origEndDate and origEndDate are "nothing" this statement is false (well when I run it in the watch window it comes back as nothing)!I don't understand why this is the case because I was under the impression doing an "=" compares the two values and as they are the same surely it should be true? What syntax should I be using as in C# I can do the above as so:

if (origEndDate == origEndDate) { }

and it will come back as true.

View 4 Replies

VS 2010 Nullable DateTime?

Jun 3, 2010

For a project I need to convert a date field in my SQL Server 2008 Database into a VB.net ListOf. Most of the records in StartDate field are NULL. VB.net doesn't recognize null values for DateTime.I need the NULL values to be dismissed, as they will be returned in a ListOf for a web service that I'm creating.

Here is my syntax and a sample of the current returned values in the XML message of the ListOf:

Class Property StartDate() As System.Nullable(Of DateTime) = Nothing
asmx.vb myUserRoleAppInfo.StartDate = myPermissionUser.StartDate
XML Message (Listof)

[Code]...

View 4 Replies

C# - DateTime Nullable Exception As A Parameter?

May 8, 2009

I have a Search Form that can search by a few different fields. The problem field is birthDate. On the form it is a string. In the SQL 2005 db it is a DateTime that can be null.

The code below is sequential as far as declaring the variable on the form and then setting it. Then the call to the BLL and then the call to the DAL.

On this line -->

dgvSearchResults.DataSource =ConnectBLL.BLL.Person.Search(_firstName,_middleName,_lastName,_sSN, (DateTime)_birthDate,_applicationID,_applicationPersonID,_fuzzy);

[Code]....

View 4 Replies

Nullable DateTime And Ternary Operator?

Nov 15, 2010

I'm having problems with a Nullable DateTime in VB.NET (VS 2010).

Method 1
If String.IsNullOrEmpty(LastCalibrationDateTextBox.Text) Then
gauge.LastCalibrationDate = Nothing

[code].....

View 2 Replies

C# - Set System.nullable Of Datetime As An Optional Parameter In A Subroutine?

Nov 13, 2011

I tried the following, but i get the error

constant expression is required
Public Sub ExampleSub(ByVal Test as string,
Optional ByVal fromDate As System.Nullable(Of DateTime) = Date.Today)
'A Great sub!

[Code].....

View 3 Replies

DateTimePicker Bound To Nullable DateTime Field But No Null?

Apr 7, 2010

I have a date time picker bould to a Nullable Datetime field in a sql server datatable. The ShowCheckBox option is set to true. If the user unchecks the checkbox on the datetimepicker I would like to the field to be set back to null in the DataTable. The default behaveour does not seem to do this and there is no specific event for the uncheck.

Private Sub dtpCertDate_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dtpCertDate.ValueChanged
If dtpCertDate.Focused Then

[code].....

View 4 Replies

.net - Grouping Using LINQ?

Feb 5, 2010

I'm having a heck of a time with transforming a simple SQL Query into a LINQ query(using vb btw)

Here is my SQL:
SELECT USRDEFND5
FROM int_gp_employee
GROUP BY USRDEFND5

[Code]...

I've tried a number of different variations of the LINQ. My current statement is:

From b In xmlFile...<row> Group b...<usrdefnd5> By b...<usrdefnd5> INTO group when I foreach through the resulting collection, EVERY line (17000) shows up.

View 2 Replies

.net - Linq Nested Grouping?

Jul 7, 2009

I've a large table of Items and I need to organize them by Category, then by Year and then by Month.Item has CategoryID and Dated properties.I got this far:

Dim Items = From Item In DB.Items _
Group By CategoryID = Item.CategoryID _
Into Categories = Group _
Order By CategoryID

But where I put the:

Group By Year = Year(Item.Dated)

and the

Group By Month = Month(Item.Dated)

The final result should be something like this:

For Each Category in Categories
For Each Year in Category.Years

[code].....

View 2 Replies

Datatable Grouping Using Linq?

May 25, 2011

I'm completely dense here, but I'm trying to get some stats from a DataTable. One of the columns in the datatable is called "colour".I need to find out how many of each instance of "colour" are in the datatable.

I'm trying:
Dim q = From p In PGWorkingDataTable _
Group p By p("colour") Into Group _

[code].....

View 2 Replies

Counting Orders And Grouping Them, Linq To Sql?

Aug 15, 2011

I have a table called Ordersthe table has many rows but im only interested in two in particular.I want to query the table so it returns the average ordered count of each producti want to know what is the average count of the ordered products, but now in total but per productID instead.

View 1 Replies

Grouping A Generic List Via LINQ?

Jun 26, 2011

I need to take a collection and group it via Linq but all the examples I've seen fail in some manner or other with some syntax difference that I can't quite lick.

My collection:

Dim a As New List(Of ProcessAlert)
a.Add(New ProcessAlert("0000112367", "5551110000@txt.att.net", "Alert", 2))
a.Add(New ProcessAlert("0000112367", "5551110000@txt.att.net", "Document", 2))

[Code].....

View 1 Replies

LINQ To SQL Grouping Multiple Columns With A Distinct Row

Aug 9, 2010

I have the following table structure. I want to select distinct CustomerId and CustomerName, TotalCost.[code]

View 2 Replies

Return Max Record Count By Grouping In Linq?

Nov 9, 2011

I'm very new to linq and I'm trying to come up with a linq query against a dataset that will return a max count value based on grouping records.[code]...

View 1 Replies

Converting A Traditional SQL Aggregate Query Into A LINQ One - SUM Grouping ?

May 24, 2010

I'm having trouble getting my head around converting a traditional SQL aggregate query into a LINQ one. The basic data dump works like so:

Dim result =
(From i As Models.InvoiceDetail In Data.InvoiceDetails.GetAll
Join ih As Models.InvoiceHeader In Data.InvoiceHeaders.GetAll On i.InvoiceHeaderID Equals ih.ID

[CODE].....................

What I need to really be getting out is ih.Period (a value from 1 to 12) and a corresponding aggregate value for i.ExtendedValue. When I try to Group ih I get errors about i being out of scope/context.

View 1 Replies

Linq Grouping With Anonymous Types And Option Strict

Apr 24, 2012

I've got the below, where I'm grouping a collection by a propery, then wanting to access the properties of my group. Problem I have is with the anonymous typing. Because of option strict I have to give an explicit type but I can't work out what the type should be. The below doesn't compile because t.HeadAccountKey isn't a value (as t has a type of object). So either I need do some casting or my linq selector is wrong,

[Code]....

View 1 Replies

Compare Nullable Types In WHERE Clause Of Linq To Sql .NET?

May 4, 2012

I am trying to query for records where that column IS NULL:

Dim UnassignedSubSvc =
From c In CurrentContext.SubService
Where c.Product.ProductSubServiceId **is null**
Select c).ToList()

View 1 Replies

Filtering A Collection With Linq And Multiple Criteria?

Jun 7, 2012

On my view there is a datatable holding a collection of ServerRow and 4 textboxes (Hostname, OS, Location, Zone). When the user types into any of the 4 boxes I want to immediately filter this list. I have this code setup and ready to go that on the set method of each textbox property I call the filter method.

Now onto the problem: if I have 4 criteria that means I have 2 to the power of 4 different scenarios. What I would like to do is write a linq statement with all of these scenarios dealt with such that if any of the properties are NullOrEmpty they will not be used in the Where clause and on the flip side if there is a value the corresponding field will be searched with a Contains.

Example

AvailableCis = New ObservableCollection(Of ServerRow)
(_CiData.Where(Function(ci) ci.OS.ToUpper
.Equals(_selectedOS.ToUpper) AndAlso
ci.HostName.ToUpper.Contains(_ciNameFilterText.ToUpper))
.OrderBy(Function(a) a.CiName))

This example shows how it works with 2 criteria and both of those criteria are set.

View 1 Replies

LINQ Query - Join Tables On Nullable Columns

Apr 17, 2011

How to JOIN tables on nullable columns? I have following LINQ-query, RMA.fiCharge can be NULL:
Dim query = From charge In Services.dsERP.ERP_Charge _
Join rma In Services.dsRMA.RMA _
On charge.idCharge Equals rma.fiCharge _
Where rma.IMEI = imei
Select charge.idCharge

I get a "Conversion from type 'DBNull' to type 'Integer' is not valid" in query.ToArray():
Dim filter = _
String.Format(Services.dsERP.ERP_Charge.idChargeColumn.ColumnName & " IN({0})", String.Join(",", query.ToArray))
So I could append a WHERE RMA.fiCharge IS NOT NULL in the query. But how to do that in LINQ or is there another option?

The problem was that the DataSet does not support Nullable-Types but generates an InvalidCastException if you query any NULL-Values on an integer-column. The modified LINQ-query from dahlbyk works with little modification. The DataSet generates a boolean-property for every column with AllowDbNull=True, in this case IsfiChargeNull.

Dim query = From charge In Services.dsERP.ERP_Charge _
Join rma In (From rma In Services.dsRMA.RMA _
Where Not rma.IsfiChargeNull
Select rma)
On charge.idCharge Equals rma.fiCharge _
Where rma.IMEI = imei
Select charge.idCharge

View 2 Replies

Error - Soap Serializer Does Not Support Serializing Generic Types : System.Nullable`1[System.DateTime]

Oct 2, 2009

Im working on my first n-tier application. I am trying to serialize a structure and Im getting an error"Soap Serializer does not support serializing Generic Types : System.Nullable`1[System.DateTime]."Here is the structure that is being serialized
Namespace Structures

<Serializable()> _
Public Structure structAllergy
Public AllergyID As String
Public ProfileID As String

[code]....

The bold line is the line that is throwing the error.

View 1 Replies

Asp.net - Select Distinct Rows From A Datatable With Criteria Involving Multiple Columns Using LINQ

Mar 9, 2012

I have a datatable as shown in the figure. Let me explain my required based on this image. I have 7 rows of data. The rows 1 and 2 contains columns till UnitSqcNo same. I want only row 3 among the two. In general I want select all the rows with distinct model, unittype, unit and rest with greater CompId. ie the table should look like

View 1 Replies

Calculate DateTime With LINQ To SQL?

Aug 17, 2010

I have two tables TimeSheet and TimeRecord. TimeRecord has Foreign Key TimeSheetId of TimeSheet. The following time-logs are from TimeRecord[code]...

View 3 Replies

Asp.net - Linq Group By An Entity And Then Order By The Grouped (nullable) Entity

Jul 27, 2011

I am trying to build a survey engine from an existing database design which is like this.

[Code]...

The line Order By Key.RecordOrder throws a null reference exception and I can understand why. Can someone advise on how to resolve this by just modifying this one query? I am fairly new to LINQ and the necessity to write this project

[Code]...

View 1 Replies

Linq To SQL - How To Return Values For A Single Date In Datetime Format

Nov 30, 2011

I am trying the following to select a long date, but becase the value is stored in SQL database as DateTime I am unable to return any results unless minutes and seconds match perfectly...I then tried to use 2 calendars and have the same issue with the DateTime format..

CODE:

View 1 Replies

Convert String To Datetime & Calculate The Datetime?

Mar 23, 2011

how to convert string to datetime and calculate date

View 3 Replies

Match A Certain DateTime Value With Current System DateTime

May 7, 2010

I'm trying to match a certain DateTime value with the current system DateTime. I have a timer and a label on a form. Timer interval is set to 1000. When the form loads, the timer starts ticking. As soon as the current DateTime matches the value of the variable, it shows a message in the label. When I'm writing the following code, the values don't match even if the current system DateTime is equal to the variable. Label1 isn't showing 'Times Matched':[code]The default format of 'Now' is the same as I have stored in dtmVar variable. So there's no question of format mismatch. Does that mean 'Now' is not actually a DateTime property? Provided, my O.S. is Windows Vista Ultimate and all date/time settings are set to default.

View 1 Replies

Match A Certain DateTime Value With The Current System DateTime?

May 1, 2010

I'm trying to match a certain DateTime value with the current system DateTime. I have a timer and a label on a form. Timer interval is set to 1000. When the form loads, the timer starts ticking. As soon as the current DateTime matches the value of the variable, it shows a message in the label.

When I'm writing the following code, the values don't match even if the current system DateTime is equal to the variable. Label1 isn't showing 'Times Matched':

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim dtmNow As DateTime

[Code]....

Why is it so? The default format of 'Now' is the same as I have stored in dtmVar variable. So there's no question of format mismatch. Does that mean 'Now' is not actually a DateTime property? Provided, my O.S. is Windows Vista Ultimate and all date/time settings are set to default.

View 1 Replies

Update Datetime Field With Empty Datetime?

Aug 8, 2011

datetime1 and datetime2now two fields are have data ( date )in table recordi want to update only datetime2 is an emptyi am using visual basic 2010 ( visual studio 2010

View 1 Replies

Pass A Nullable Valuetype Into A Non Nullable Valuetype?

Sep 17, 2009

I accidently wrote some code today that was like this[code]...

I immediately noticed the issue, but I had already hit the run button. It compiled successfully, I ran it through to the section and it threw an exception.

You can't do this in C#, it gives a compile error "cannot convert from 'int?' to 'int'".

Is there an 'Option Explicit' type switch that I can turn on to ensure that this sort of error does not occur again?

View 1 Replies

C# - Compare Datetime.Now With A Datetime Variable

Dec 27, 2010

I try to compare Datetime.Now with a Datetime variable I set, using the Datetime.CompareTo() method. I use a timer to compare these every second and display the result, but as the current time approaches the time I set, the result changes from 1 to -1, but never 0, which means these two are never equal. I'm suspecting the Datetime structure contains milliseconds?

View 7 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved