rewrite Linq to SQL - sql

I have a linq query in VB.NET:
Dim i = ( _
From o In model.DUIMAINs _
.Include("VIOLATOR") _
.Include("ARRESTINGOFFICER") _
.Include("DR15") _
Where _
o.BREATHRESULT Is Nothing _
Order By _
o.ARRESTDATETIME _
)
and I am checking the tables by the writing the corresponding SQL query
SELECT
*
FROM
"DUI" ."DUI_MAIN" main,
"DATA"."TBL_TRAFFIC_PERSON" violator,
"HRIS"."TBL_PERSONNEL" ARRESTINGOFFICER,
"DUI" ."DR15" dr15,
"DUI" ."BREATHRESULTS" BREATHRESULTS
WHERE
main.Duiguid = 'deaee240-cdc3-4b50-b215-51307e7d96a5'
and
main.Duiguid = violator.seq_guid
and
main.arrestingofficerusername = ARRESTINGOFFICER.USERNAME
and
main.Duiguid = dr15.Duiguid
and the results are coming back correct (at least the tables are being populated correctly) however for the where clause I have question
QUESTION?
How do i write the
Where o.BREATHRESULT Is Nothing
in my SQL Code where BREATHRESULT is a table. Common Key is Duiguid.

Related

LINQ query update to accommodate changes

I need help in combining below SQL to code
Dim queryPersons = Query.From("ADSAccountInADSGroup") _
.Where(Function(t) t.Column("UID_ADSAccount") = uidAdsAccount) _
.SelectAll()
I'm successfull only until UID_ADsAccount = '4f58406f-8823-4530-b763-d344fc9093ed')
I need to append below piece of code as well to Dim queryPersons
and uid_adsgroup not in(select uid_adsgroup from adsgroup where cn like 'Domain%'))
and (XMarkedForDeletion <> 2) and (XOrigin = 1)))

Linq query to display unique set of names for current data set

I have a linq query that is used to display the list of requests from multiple users.And a Requestor can have multple requests(So the grid can have same Requestor multiple times). Now i am creating a dropdown list with unique Requestor that are displayed on the grid.(issue is i am not getting the distinct list but getting all the Requestor multiple times). Below is the linq query i am unsing.Can anyone suggest with correct linq query.
Dim rqstQry = From x In db.Request_vws _
Order By x.RequestID Descending _
Select x.RequestID,
Descr = x.Descr, _
RequestorName = String.Format("{0} {1}", x.FIRST_NAME, x.LAST_NAME), _
RelatedTask = GetTaskDescr(x.WorkID, x.TaskLabel, x.TaskDescr), _
RequestDescr = GetRequestDescr(x.RequestType), x.SubmitDttm, x.UpdatedDttm, _
x.ChangeDttm, _
x.MigrTimeStr, x.MigrApptTime, _
x.Requestor Ditinct
DataBind:
RequestorCB1.DataSource = rqstQry
RequestorCB1.DataTextField = "Requestor" RequestorCB1.DataValueField = "REquestor"
RequestorCB1.DataBind()
Need distinct user in the dropdownlist
Put parentheses around the LINQ query and append .Distinct()
Dim rqstQry = (From x In db.Request_vws _
Order By x.user
Select x.user).Distinct()
If you are including Request stuff in the result, then you cannot get distinct users (as Gert Arnold points out in his comment). Only include columns related to users.
If you still need information on requests then you must limit this information to one record per user. You would use a group by and use an aggregate in order to select a request (the first one, the last one etc.).
Got this by using the below query.
Dim rqstQry = (From x In db.Request_vws _
Order By x.RequestID Descending _
Select x.RequestID,
Descr = x.Descr, _
RequestorName = String.Format("{0} {1}", x.FIRST_NAME, x.LAST_NAME), _
RelatedTask = GetTaskDescr(x.WorkID, x.TaskLabel, x.TaskDescr), _
RequestDescr = GetRequestDescr(x.RequestType), x.SubmitDttm, x.UpdatedDttm, _
x.ChangeDttm, _
x.MigrTimeStr, x.MigrApptTime, _
x.Requestor). Distinct()
Dim rqstQry2 = (From y In rqstQry _
Select y.Requestor, y.RequestorName).Distinct()

LINQ Join between datatables, two untyped fields

I'm querying two databases and trying to join the result sets and query out of them using LINQ. It seems it would be an easy task, but without doing an explicit join I'm having major performance issues. When I do the explicit join, I am having trouble with VB syntax for making things explicit types. Working Code, Cleaned:
For Each CurrRow In ResultsA.Tables(15).Rows
CurrDate = CurrRow("Date")
CurrID = CurrRow("ID")
CurrVal = CurrRow("Val")
Dim ResultsB = From SMW In DataSetA.Tables(0).AsEnumerable() _
Where SMW("ID") = CurrScheduleID And SMW("Time") = CurrProfileDate _
Select UTC_TS = SMW("Time"), Value = (SMW("VALUE") / 1000), Time_Zone = SMW("Time_Zone"), ID = SMW("ID")
Dim CurrentResult As Object
Dim boolSchedDateFound As Boolean = False
For Each CurrentResult In ResultsB
If CurrentResult.Value <> CurrVal Then
'LogIntegrityCheckErrorRow()
End If
boolSchedDateFound = True
Next
Next
This takes FOREVER to run with 100,000 rows.
I've been trying to rewrite this as:
Dim MismatchRows = From TableAData In DataSetA.Tables(0).AsEnumerable() Join TableBData In DataSetB.Tables(15).AsEnumerable() _
On New With {.TableAID = Convert.ToInt32(TableAData("ID")), .TableATime = Convert.ToDateTime(TableAData("Date"))} _
Equals New With {.TableBDID = Convert.ToInt32(TableBData("ID")), .TableBTime = Convert.ToDateTime(TableBData("Time"))} _
Select .................. (Hard to clean up, but this isn't the part that's failing)
And I'm having a bear of a time with it. The fundamental problem is the lack of strong typing. I've looked, but there seems to be little advice because most people doing this build EF on the data. Which isn't a terrible idea, but would require a bunch of re-engineering. So. Problem in front of me, how do I remove the error:
'Equals' cannot compare a value of type '<anonymous type> (line 2641)' with a value of type '<anonymous type> (line 2642)'.
Thank you so much for your help.
Have you tried this?
Dim MismatchRows = From TableAData In ei _
Join TableBData In e2 On _
TableAData("ID") Equals TableBData("ID") And TableAData("Data") Equals TableBData("Time")
Select .......
db.tb_DeviceGeFenceDetail.Join(db.tb_InventoryLog, Function(gfd) gfd.DeviceID, Function(il) il.deviceId, Function(gfd, il) New From { _
gfd.GeFenceLat1, _
gfd.GeFenceLng1, _
gfd.GeFenceLat2, _
gfd.GeFenceLng2, _
il.deviceName, _
il.DeviceIcon, _
gfd.DeviceID, _
il.id _
}).ToList().Where(Function(y) intValues.Contains(y.id))
you can try joining tables something like this.

LINQ query with multiple joins throwing null reference error

I have a LINQ query with 3 joins and a grouping operation that is throwing a null reference error. In the below query (I'm sorry for the length) if you skip to the 'eDTK_PDP_Description' field, it's that one that it causing the problem. I realize that I have the DefaultIfEmpty specification for the last join but I thought if I assign a value to the field from that join if it's null that should solve the problem. What am I doing wrong here? Thanks!
Dim UpdateSiebelPDP1 = From j In ( _
From PDP In SiebelMultPDPDescNoNull _
Group Join Siebel In ProdBase _
On PDP.Siebel_PDP_Code Equals Siebel.Siebel_PDP_Code _
Into g = Group _
From Result In g _
Group Join EDTK In eDTKBase _
On PDP.Siebel_PDP_Code Equals EDTK.eDTK_PDP_Code _
Into h = Group _
From Result2 In h _
Group Join EDTK2 In EDTKPDPOneDescDet _
On PDP.Siebel_PDP_Code Equals EDTK2.PDP_Description _
Into i = Group _
From Result3 In i.DefaultIfEmpty _
Select Result.Siebel_PLI, _
Result.Siebel_PDP_Code, _
Update_DAD_Flag = If(Result.Siebel_DAD_Flag Is Nothing, "Yes", "No"), _
System = "Siebel", _
PDD_PDP_Description = If(Result2.PDD_PDP_Description Is Nothing, _
"", Result2.PDD_PDP_Description), _
Siebel_PDP_Description = "Multiple", _
eDTK_PDP_Description = If(Result3.PDP_Description Is Nothing, _
"Multiple", Result3.PDP_Description)) _
Group j By j.Siebel_PLI, _
j.Siebel_PDP_Code, _
j.Update_DAD_Flag, _
j.System, _
j.PDD_PDP_Description, _
j.Siebel_PDP_Description, _
j.eDTK_PDP_Description _
Into k = Group _
Select New With { _
Siebel_PLI, _
Siebel_PDP_Code, _
Update_DAD_Flag, _
System, _
PDD_PDP_Description, _
Siebel_PDP_Description, _
eDTK_PDP_Description}
The problem is that Result3 is null and you're trying to access a property on it. That's why your if isn't actually solving the problem. You can't check if Result3.SomeField is null if Result3 is null because the attempted access causes a NullRefereceException so basically, you need to check if Result3 is null before you go about trying to use it for assignment. If it is, then you should use some default value. I'll give a general idea, although it's not going to be VB cause I don't write that nonsense :P
if (Result3 != null)
eDTK_PDP_Description = Result3.SomeField;
else
eDTK_PDP_Description = defaultValue;
You'll have to decide for yourself how to you want to put this check into your query. The whole thing is a bit much for me and I don't know what you would want to assign there in the case that Result3 is null.

linq query dynamically add where condition?

I want to filter records dynamically on user choice. The user may choose to show the debit amount greater than credit or credit amount greater than debit. Accordingly I want to put a condition similar to either totDebit>totCredit orTotCredit>totDebit`
Dim query = _
From product In Bills.AsEnumerable() _
Group product By accode = product.Field(Of String)("ACCODE"), _
BILLNO = product.Field(Of String)("BILLNO") Into g = Group _
Let totDebit = g.Sum(Function(proudct) proudct.Field(Of Decimal)("DEBIT")) _
Let totCredit = g.Sum(Function(proudct) proudct.Field(Of Decimal)("CREDIT")) _
Select New With _
{ _
.ACCODE = accode, _
.billno = BILLNO, _
.TOTALDEBIT = totDebit, _
.TOTALCREDIT = totCredit, _
.BALNACE = totDebit - totCredit _
}
How can this be done?
In the code you h ave shownm you've merely built a query; you haven't executed it yet. And, at any point before you excute it, you may continue to build it:
Dim query = _
From product In Bills.AsEnumerable() _
Group product By accode = product.Field(Of String)("ACCODE"), _
' etc as above....
If onlyCredits Then
query = query.Where(Function(proudct) product.TOTALCREDIT > product.TOTALDEBIT)
Elseif onlyDebits Then
query = query.Where(Function(proudct) product.TOTALCREDIT < product.TOTALDEBIT)
Endif
Note, I'm a C# guy, so please forgive minor syntax errors....
I think you're looking for Dynamic Query Library. Not included in Linq but availble for download from Scott Guthrie's blog:
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx
Both the VB and C# DynamicQuery
samples include a source
implementation of a helper library
that allows you to express LINQ
queries using extension methods that
take string arguments instead of
type-safe language operators.
You can apply strings to filter the exection:
myData.DynamicWhere(string.Format("{0}.Contains(\"{1}\")", filter.field, filter.data.value));