I'm fairly new to LINQ in general but I've managed to figure things out so far to get the result I want/need. The LINQ2SQL query below produces the desired results in which there are Location objects, each with their own collection of Units. The initial variable declarations are done to setup the values that I need to query from and should not be relevant to my issue but are needed for context.
The problem I'm having is that there are 400+ locations, and the current way I have the query structured, it is hitting the database for each one instead of one big query. This is causing performance to suffer greatly, taking 30+ seconds for the full result to come back which is unacceptable. I have a stored procedure SQL query that returns the results in only a second or two.
Is there a way to restructure this query so that I'm not hitting the database for each location? I'm sure it's caused by the extra "ToList()" on the Units subquery but I don't know how to shape the result without the ToList(). Any performance tweaking would be a HUGE help. Thanks for any help!
Dim curNames1 = (From ons In dc.organization_names _
Where ons.eff_date <= ssDate _
Order By ons.eff_date Descending _
Group ons By ons.organization_id Into gNames = Group _
Select New With { _
Key .Key = organization_id, _
.Result = gNames.Take(1)}) _
.SelectMany(Function(a) (a.Result))
Dim curLocs1 = (From oLocs In dc.organization_locations _
Where oLocs.eff_date <= ssDate _
Order By oLocs.eff_date Descending _
Group oLocs By oLocs.organization_id Into gLocs = Group _
Select New With { _
Key .Key = organization_id, _
Result = gLocs.Take(1)}) _
.SelectMany(Function(a) (a.Result))
Dim curStatuses1 = (From oEDate In dc.organization_conversion_dates _
Where oEDate.edate <= ssDate _
Order By oEDate.edate Descending _
Group oEDate By oEDate.organization_id Into gEDates = Group _
Select New With { _
Key .Key = organization_id, _
.Result = gEDates.Take(1)}) _
.SelectMany(Function(a) (a.Result))
Dim curCommand1 = (From oCommand In dc.organization_service_assigneds _
Where oCommand.eff_date <= ssDate _
Order By oCommand.eff_date Descending _
Group oCommand By oCommand.organization_id Into gCmds = Group _
Select New With { _
Key .Key = organization_id, _
.Result = gCmds.Take(1)}) _
.SelectMany(Function(a) (a.Result))
Dim curComponent1 = (From oCompo In dc.organization_compos _
Where oCompo.eff_date <= ssDate _
Order By oCompo.eff_date Descending _
Group oCompo By oCompo.organization_id Into gCompos = Group _
Select New With { _
Key .Key = organization_id, _
.Result = gCompos.Take(1)}) _
.SelectMany(Function(a) (a.Result))
ss.Locations = New ObservableCollection(Of Location)(( _
From map In dc.MapBackgrounds Where map.MapID = options.Map _
Let Locs = map.Schemes.SchemeLocations _
From SchemeLoc In Locs _
Where (options.Locations.Count = 0 Or _
options.Locations.Contains(SchemeLoc.Location.ID)) _
Select New Location With { _
.ID = SchemeLoc.Location.ID, .Name = SchemeLoc.Location.Location, _
.Y = SchemeLoc.Y, .X = SchemeLoc.X, _
.Country = New Country With _
{.ID = SchemeLoc.Location.Countries.ID, _
.Name = SchemeLoc.Location.Countries.country}, _
.State = If(SchemeLoc.Location.State = -1, Nothing, _
New USState With {.ID = SchemeLoc.Location.States.ID, _
.Name = SchemeLoc.Location.States.state, _
.Abbreviation = SchemeLoc.Location.States.state}), _
.Units = New ObservableCollection(Of MillitaryUnit)(( _
From curLoc In curLocs1 _
Where curLoc.location = SchemeLoc.Location.ID _
From curName In curNames1 _
Where curName.organization_id = curLoc.organization_id _
And (options.UnitSizes.Count = 0 Or _
options.UnitSizes.Contains(curName.UnitSize)) _
And (options.UnitTypes.Count = 0 Or _
options.UnitTypes.Contains(curName.UnitType)) _
From curEDate In curStatuses1 _
Where curEDate.organization_id = curLoc.organization_id _
And (options.Statuses.Count = 0 Or _
options.Statuses.Contains(curEDate.status)) _
From curCmd In curCommand1 _
Where curCmd.organization_id = curLoc.organization_id _
And (options.Commands.Count = 0 Or _
options.Commands.Contains(curCmd.service_assigned)) _
From curCompo In curComponent1 _
Where curCompo.organization_id = curLoc.organization_id _
And (options.Components.Count = 0 Or _
options.Components.Contains(curCompo.compo)) _
From curTable In curLoc.Organization.organization_tables _
Where curTable.organization_id = curLoc.organization_id _
And (options.Tables.Count = 0 Or _
(options.Tables.Contains(curTable.table_id) Or _
curTable.Tables.Any(Function(a) (options.Tables.Contains(a.parent_id))))) _
Select New MillitaryUnit With { _
.ID = curLoc.organization_id, _
.Name = curName.name, _
.IconPath = curName.icon, _
.ConversionStatus = curEDate.Status1.status, _
.ServiceCommand = curCmd.Service_Assigneds.service_assigned, _
.Component = curCompo.Components.compo}).Distinct().ToList())}).ToList())
UPDATE (3/3/2009 10:58 AM):
I managed to get the data back in one query using the query below but it's a flat table result. How can I shape this so that the organization stuff becomes hierarchical under each location? I believe I want to use something like "Group Join" but I'm not familiar with how that works. The location info is everything up to the "OrgID" column. I need to shape this data into a collection of Locations that each have a "Units" property which is a collection of the organizations that are at that location. Any guidance?
Dim locationsquery = (From map In dc.MapBackgrounds Where map.MapID = 1 Let Locs = map.Schemes.SchemeLocations _
From SchemeLoc In Locs Join curLoc In curLocs1 On SchemeLoc.LocID Equals curLoc.location _
Join curName In curNames1 On curLoc.organization_id Equals curName.organization_id _
Join curStatus In curStatuses1 On curLoc.organization_id Equals curStatus.organization_id _
Join curCommand In curCommand1 On curLoc.organization_id Equals curCommand.organization_id _
Join curComponent In curComponent1 On curLoc.organization_id Equals curComponent.organization_id _
Select New With {.LocationID = SchemeLoc.LocID, .X = SchemeLoc.X, .Y = SchemeLoc.Y, _
.LocationName = SchemeLoc.Location.Location, _
.CountryID = SchemeLoc.Location.Countries.id, .CountryName = SchemeLoc.Location.Countries.country, _
.StateID = SchemeLoc.Location.State, .StateName = SchemeLoc.Location.States.state, .StateAbbrev = SchemeLoc.Location.States.state, _
.OrgID = curLoc.organization_id, _
.OrgName = curName.name, _
.OrgLocID = curLoc.location, _
.IconPath = curName.icon, _
.ConversionStatus = curStatus.status1.status, _
.CurCmd = curCommand.service_assigneds.service_assigned, _
.CurCompo = curComponent.components.compo})
Instead of exposing the member as a List<T>, change the property type to an IEnumerable<T> or an IQueryable<T>. Then, you can remove the calls to ToList and your query should be able to be executed completely on the server in one shot.
Also, this kind of code is where LINQ to SQL starts to break down, IMO. I think that if you have a stored procedure which will give you the desired results, then you should use that, and just have LINQ to SQL handle the mapping of the returned data to your objects.
So I ended up redoing things and came up with the following solution which only queries the database twice and is MUCH faster:
Dim locationsOnly = (From map In dc.MapBackgrounds Where map.MapID = 1 Let Locs = map.Schemes.SchemeLocations _
From SchemeLoc In Locs _
Where (options.Locations.Count = 0 Or options.Locations.Contains(SchemeLoc.LocID)) _
Select New With {.LocationID = SchemeLoc.LocID, .X = SchemeLoc.X, .Y = SchemeLoc.Y, _
.LocationName = SchemeLoc.Location.Location, _
.CountryID = SchemeLoc.Location.Countries.ID, .CountryName = SchemeLoc.Location.Countries.country, _
.StateID = SchemeLoc.Location.State, .StateName = SchemeLoc.Location.States.state, .StateAbbrev = SchemeLoc.Location.States.state}).ToList()
Dim orgsOnly = (From curLoc In curLocs1 _
Join curName In curNames1 On curLoc.organization_id Equals curName.organization_id _
Join curStatus In curStatuses1 On curLoc.organization_id Equals curStatus.organization_id _
Join curCommand In curCommand1 On curLoc.organization_id Equals curCommand.organization_id _
Join curComponent In curComponent1 On curLoc.organization_id Equals curComponent.organization_id _
Join curTable In dc.organization_tables On curLoc.organization_id Equals curTable.organization_id _
Where (options.UnitSizes.Count = 0 Or options.UnitSizes.Contains(curName.UnitSize)) _
And (options.UnitTypes.Count = 0 Or options.UnitTypes.Contains(curName.UnitType)) _
And (options.Statuses.Count = 0 Or options.Statuses.Contains(curStatus.status)) _
And (options.Commands.Count = 0 Or options.Commands.Contains(curCommand.service_assigned)) _
And (options.Components.Count = 0 Or options.Components.Contains(curComponent.compo)) _
And (options.Tables.Count = 0 Or (options.Tables.Contains(curTable.table_id) Or curTable.Tables.Any(Function(a) (options.Tables.Contains(a.parent_id))))) _
Select New With {.OrgLocID = curLoc.location, _
.MilUnit = New MillitaryUnit With { _
.ID = curLoc.organization_id, _
.Name = curName.name, _
.IconPath = curName.icon, _
.ConversionStatus = curStatus.Status1.status, _
.ServiceCommand = curCommand.Service_Assigneds.service_assigned, _
.Component = curComponent.Components.compo}}).Distinct().ToList()
ss.Locations = New System.Collections.ObjectModel.ObservableCollection(Of Location)((From loc In locationsOnly _
Group Join org In orgsOnly On loc.LocationID Equals org.OrgLocID Into Orgs = Group _
Select New Location With { _
.ID = loc.LocationID, _
.Name = loc.LocationName, _
.X = loc.X, _
.Y = loc.Y, _
.Country = New Country With {.ID = loc.CountryID, .Name = loc.CountryName}, _
.State = New USState With {.ID = loc.StateID, .Name = loc.StateName, .Abbreviation = loc.StateAbbrev}, _
.Units = New System.Collections.ObjectModel.ObservableCollection(Of MillitaryUnit)((From curOrg In Orgs _
Select curOrg.MilUnit).ToList())}).ToList())
Thanks for your help casperOne!
Related
In my master workbook I have 1 table in each one of my 4 sheets and in sheet2 and sheet4 I have a couple of columns with IF and VLOOKUP functions at the right of the table.
I am trying to do the following:Clear content from the 4 tables while maintaining only one row of formulas (in sheet 2 and 4), Copy the range I want from a table in sheet1 of another workbook (repeat for other sheets), And paste into the table of sheet1 of master workbook (repeat for other sheets), Autofill the formulas of the remanining columns (only in sheet 2 and 4).
While the code does it's job, it takes almost 2 hours to perform this task! Even the Clearcontent of sheet2 takes 8 minutes for just 250 rows which seems ridiculous long time! Sheet1 has 1000 rows, sheet2 has 250, sheet3 has 1000, sheet4 has 26k rows.
Code seems too big for what it does. What can I do to optimise and speed up the code? Any viable work around or is this normal? I have tried Application.Calculation = xlCalculationManual but no improvement.
Sub LoopThroughDirectory()
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Dim MyFile As String
Dim erow1
Dim erow2
Dim erow3
Dim erow4
Dim Filepath As String
Dim wkb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim sht3 As Worksheet
Dim sht4 As Worksheet
Dim ero2 As Long
Dim ero4 As Long
Dim lastero1 As Long
Dim lastero2 As Long
Dim lastero3 As Long
Dim lastero4 As Long
Folha1.Activate
Folha1.Range(Cells(3, 1), Cells(99999, 173)).ClearContents
Folha1.Range(Cells(2, 1), Cells(99999, 173)).ClearContents
Folha2.Activate
Folha2.Range(Cells(3, 1), Cells(99999, 150)).ClearContents
Folha2.Range(Cells(2, 1), Cells(99999, 137)).ClearContents
Folha3.Activate
Folha3.Range(Cells(3, 1), Cells(99999, 197)).ClearContents
Folha3.Range(Cells(2, 1), Cells(99999, 197)).ClearContents
Folha4.Activate
Folha4.Range(Cells(3, 1), Cells(99999, 152)).ClearContents
Folha4.Range(Cells(2, 1), Cells(99999, 108)).ClearContents
Filepath = "C:\Users\carlos\Downloads\Projectos\Teste\"
MyFile = Dir(Filepath)
Do While MyFile = "Dados Projectos New"
If MyFile = "Dados Projectos_Master.xlsm" Then
Exit Sub
End If
Set wkb = Workbooks.Open(Filepath & MyFile)
Set sht1 = wkb.Sheets("Encomendas")
Set sht2 = wkb.Sheets("Projectos")
Set sht3 = wkb.Sheets("Casos")
Set sht4 = wkb.Sheets("Actividades Serviço")
wkb.Activate
sht1.Activate
With Sheets("Encomendas") 'Last row of the first sheet I want to copy
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastero1 = .Range("A:fq").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End If
End With
Range("a2:fq" & lastero1).Copy
Folha1.Activate
'last row of the first sheet of master workbook I want to paste
erow1 = Folha1.Cells.Find("*", After:=Range(Cells(Rows.Count, 173), Cells(Rows.Count, 173)), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
ThisWorkbook.ActiveSheet.Paste Destination:=Worksheets("Encomendas").Range(Cells(erow1 + 1, 1), Cells(erow1 + 1, 173))
wkb.Activate
sht2.Activate
With Sheets("Projectos") 'Last row of the second sheet I want to copy
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastero2 = .Range("A:EG").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End If
End With
Range("a2:Eg" & lastero2).Copy
Folha2.Activate
With Sheets("Projectos") 'Last row of the second sheet of master workbook I want to paste
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
erow2 = .Range("A:EG").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End If
End With
ThisWorkbook.ActiveSheet.Paste Destination:=Worksheets("Projectos").Range(Cells(erow2 + 1, 1), Cells(erow2 + 1, 137))
With Sheets("Projectos") 'Last row of the second sheet of master workbook I want to autofill
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
ero2 = .Range("A:EG").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End If
End With
Range("EH2:ET2").AutoFill Destination:=Range("EH2:ET" & ero2)
wkb.Activate
sht3.Activate
With Sheets("Casos") 'Last row of the third sheet I want to copy
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastero3 = .Range("A:go").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End If
End With
Range("a2:go" & lastero3).Copy
'Last row of the third sheet of master workbook I want to paste
erow3 = Folha3.Cells.Find("*", After:=Range(Cells(Rows.Count, 197), Cells(Rows.Count, 197)), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Folha3.Activate
ThisWorkbook.ActiveSheet.Paste Destination:=Worksheets("Casos").Range(Cells(erow3 + 1, 1), Cells(erow3 + 1, 197))
wkb.Activate
sht4.Activate
With Sheets("Actividades Serviço") 'Last row of the fourth sheet I want to copy
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastero4 = .Range("A:dd").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End If
End With
Range("a2:dd" & lastero4).Copy
ActiveWorkbook.Close
Folha4.Activate
With Sheets("Actividades serviço") 'Last row of the fourth sheet of master workbook I want to paste
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
erow4 = .Range("A:DD").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End If
End With
ThisWorkbook.ActiveSheet.Paste Destination:=Worksheets("Actividades serviço").Range(Cells(erow4 + 1, 1), Cells(erow4 + 1, 108))
With Sheets("Actividades serviço") 'Last row of the fourth sheet of master workbook I want to autofill
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
ero4 = .Range("A:DD").Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
End If
End With
Range("de2:EV2").AutoFill Destination:=Range("de2:Ev" & ero4)
MyFile = Dir
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Issues I see so far:
Folha1.Activate
Folha1.Range(Cells(3, 1), Cells(99999, 173)).ClearContents
Folha1.Range(Cells(2, 1), Cells(99999, 173)).ClearContents
You don’t need to activate since youre quite literally telling it where to clear contents.
Range("a2:fq" & lastero1).Copy
No need to copy, you can literally saying something like “Range(“a1”).Value = Range(“C2”).Value. This also means by extension that you don’t have to paste as well.
Some of the major performance tips for macros suggest not to “Copy/Paste” as well as try to avoid “selecting” and “activating.” In fact, directly manipulating worksheets is often seen as cardinal sin.
With larger data sets that need to be moved around, storing everything in an array before dumping to new locations also saves big on time.
Hopes this helps.
I'm new to writing Macros and would love some help improving the speed on this one.
I have a sheet with 35,000+ rows, and I'm looping through it to find each instance of a value (OldSKU), grabbing the SKUSubset data associated with it (which has a variable number of rows), and pasting it into a new sheet (SubsetImporter) at the first empty row.
Right now, it can take 5 minutes to loop through and find all the instances of a SKU that shows up multiple times.
OldSKU will only ever show up in Column B. Is there a way to improve the speed of this loop? Possibly defining the range that it should search through?
Sub UpdateSKU()
Dim OldSKU As Long
Dim NewSKU As Long
Dim SKUSubset As String
Dim SubsetRange As Range
Dim aPlace As Range
Dim bPlace As Range
Dim SubsetPastePlace As Long
OldSKU = Sheets("Rollover Request").Range("A2")
NewSKU = Sheets("Rollover Request").Range("B2")
'UPDATE SUBSET IMPORTER
Sheets("Subset Exporter").Activate
Set aPlace = Cells.Find(What:=OldSKU, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
SKUSubset = Cells.Find(What:=OldSKU, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Offset(0, -1).Value
Set bPlace = aPlace
Set aPlace = Cells.Find(What:=OldSKU, After:=aPlace, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Range("A1", Cells(1, 1).SpecialCells(xlLastCell)).AutoFilter Field:=1, Criteria1:=SKUSubset
Range(ActiveSheet.UsedRange.SpecialCells(xlLastCell), Cells(2, 1)).Copy
SubsetPastePlace = Sheets("Subset Importer").Cells(Rows.Count, 1).End(xlUp).Offset(1).Row
Sheets("Subset Importer").Range("A" & SubsetPastePlace).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Sheets("Subset Exporter").Activate
Sheets("Subset Exporter").Range("A2").Select
Sheets("Subset Exporter").ShowAllData
If bPlace.Row < aPlace.Row Then
Do
SKUSubset = aPlace.Offset(0, -1).Value
Range("A1", Cells(1, 1).SpecialCells(xlLastCell)).AutoFilter Field:=1, Criteria1:=SKUSubset
Range(ActiveSheet.UsedRange.SpecialCells(xlLastCell), Cells(2, 1)).Copy
SubsetPastePlace = Sheets("Subset Importer").Cells(Rows.Count, 1).End(xlUp).Offset(1).Row
Sheets("Subset Importer").Range("A" & SubsetPastePlace).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
Sheets("Subset Exporter").Activate
Worksheets("Subset Exporter").ShowAllData
Set bPlace = aPlace
Set aPlace = Cells.Find(OldSKU, After:=aPlace, LookIn:=xlValues, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)
Loop Until aPlace.Row < bPlace.Row
End If
End Sub
Lightly-tested:
Sub UpdateSKU()
Dim OldSKU As Long
Dim NewSKU As Long
Dim SKUSubset As String
Dim SubsetRange As Range
Dim skuCells As Collection, shtExp As Worksheet, shtImp As Worksheet
Dim skuCell
Set shtExp = Sheets("Subset Exporter")
Set shtImp = Sheets("Subset Importer")
OldSKU = Sheets("Rollover Request").Range("A2")
NewSKU = Sheets("Rollover Request").Range("B2")
Set skuCells = FindAll(shtExp.Columns(2), OldSKU) 'get all instances of SKU
shtExp.Activate
For Each skuCell In skuCells
SKUSubset = skuCell.Offset(0, -1).Value
shtExp.Range("A1", Cells(1, 1).SpecialCells(xlLastCell)).AutoFilter _
Field:=1, Criteria1:=SKUSubset
shtExp.Range(shtExp.Cells(2, 1), shtExp.UsedRange. _
SpecialCells(xlLastCell)).Copy
shtImp.Cells(Rows.Count, 1).End(xlUp).Offset(1).PasteSpecial _
Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False
shtExp.ShowAllData
Next skuCell
End Sub
'return a Collection containing all cells with value [findWhat]
Function FindAll(rngToSearch As Range, findWhat As Long) As Collection
Dim rv As New Collection, f As Range, add1 As String
Set f = rngToSearch.Find(what:=findWhat, LookIn:=xlValues, Lookat:=xlWhole)
If Not f Is Nothing Then
add1 = f.Address()
Do While Not f Is Nothing
rv.Add f
Set f = rngToSearch.FindNext(after:=f)
If f.Address = add1 Then Exit Do
Loop
End If
Set FindAll = rv
End Function
i m using NHibernate 3.3 with linq. When i write a select query it results nothing.
Code for configuration and oppening session is given bleow.
Dim cfg As New Configuration()
cfg.Properties.Add(NHibernate.Cfg.Environment. _
ConnectionProvider, GetType(NHibernate.Connection. _
DriverConnectionProvider).AssemblyQualifiedName)
cfg.Properties.Add(NHibernate.Cfg.Environment.Dialect, _
GetType(NHibernate.Dialect.MsSql2012Dialect). _
AssemblyQualifiedName)
cfg.Properties.Add(NHibernate.Cfg.Environment.ConnectionDriver, _
GetType(NHibernate.Driver.SqlClientDriver). _
AssemblyQualifiedName)
cfg.Properties.Add(NHibernate.Cfg.Environment.ConnectionStringName, _
"connectionstring")
cfg.Properties.Add(NHibernate.Cfg.Environment. _
ProxyFactoryFactoryClass, GetType _
(NHibernate.Bytecode.DefaultProxyFactoryFactory). _
AssemblyQualifiedName)
Dim s2 As NHibernate.ISessionFactory = cfg.BuildSessionFactory
db = s2.OpenSession()
upto here it working fine and query is
Dim user As myClass = New myClass
Dim query = (From my_table In db.Query(Of myClass)() Where user.fname = name Select IMSDK_Users).SingleOrDefault
but query return nothing.
Please help Thanks
include these namespaces:
Imports System.Linq
Imports NHibernate
Imports NHibernate.Linq
and try this:
Dim query = (From c In db.Query(Of myClass)() Where c.fname = name Select c).FirstOrDefault()
I need to format a datetime as a shortdatestring in my LINQ To Entities query. I tried the following, but it does not work-
aryData =
(
From cert In db.LWCerts _
Select New With { _
.ToBeProcessedDate = cert.ToBeProcessedDate.ToShortDateString
}
).ToArray()
How can I get a date to return as a short date string ("ie: 08/05/2013")?
EDIT Here is the entire linq query-
aryData =
(From lwl In db.LWCertLoans _
Join c In db.Loans _
On c.LoanNum Equals lwl.LoanNum _
Join p In db.LWCertColls _
On lwl.CertID Equals p.CertID _
Join r In db.RespCntrs _
On r.BranchNum Equals c.BranchNum _
Join cert In db.LWCerts.AsEnumerable() _
On cert.LWCertID Equals lwl.CertID _
Where lwl.LoanNum = p.LoanNum _
Select New With { _
.ToBeProcessedDate = cert.ToBeProcessedDate, _
.CertType = cert.CertType, _
.CertCollID = p.CertCollID, _
.CertificateID = p.CertID, _
.LoanNumberTypeAndCurrencyCombined = c.LoanNum, _
.LoanType = c.LoanType, _
.CurrType = r.CurrType, _
.CollanteralBalance = c.ColCurBal, _
.SalesAdditions = p.Sales, _
.CreditMemos = p.Credits, _
.CashRemovals = p.NetCollect, _
.NonDilutiveAdjustment = p.PlusAdj, _
.Discounts = p.Discounts, _
.NonARCash = p.NonARCash, _
.DilutiveAdjustment = p.NegAdj, _
.LWCertCollsComments = p.Comments, _
.StatusCode = p.StatusCode, _
.CertLoanID = lwl.CertLoanID, _
.Modified = lwl.Modified, _
.LoanNum = lwl.LoanNum, _
.EffectiveDate = lwl.EffectiveDate, _
.RepWireNumber = lwl.RepWireNumber, _
.Advance = lwl.Advance, _
.ModifiedDate = lwl.ModifiedDate, _
.DDAAccountName = lwl.DDAAccountName, _
.LWCertLoansComments = lwl.Comments, _
.Comment = If(cert.CertType = 0, p.Comments, lwl.Comments)}).ToArray()
You should move the ToString from database to application, using AsEnumerable():
aryData =
(
From cert In db.LWCerts.AsEnumerable() _
Select New With { _
.ToBeProcessedDate = cert.ToBeProcessedDate.ToShortDateString
}
).ToArray()
That will take DateTime as is is from database and then format it on application side.
Dim Cozinhas as string = "1, 2, 3"
Dim FiltroCozinha() As String = Cozinhas.Split(",")
Dim Empresas = (From E In lstEmpresas _
Group Join CE In lstCozinhasEmpresas On CE.EmpresaID Equals E.EmpresaID Into CEJ = Group From CE In CEJ.DefaultIfEmpty() _
Group Join FC In lstFiltroCozinha On FC Equals CE.CozinhaID Into FCJ = Group From FC In FCJ.DefaultIfEmpty() _
Select New With {E.Nome} _
).Distinct.ToList
Throws exception "Object reference not set to an instance of an object."... but if I remove
Group Join FC In lstFiltroCozinha On FC Equals CE.CozinhaID Into FCJ = Group From FC In FCJ.DefaultIfEmpty() _
It works. How do I do left join with the array "FiltroCozinha"?
I think you are declaring and utilizing the same variable in the same line
Dim Empresas = (From E In Empresas _