Linq Entity With Return Function - vb.net

I have 2 tables:
Room_Type (ID_Room_Type, Name_Room_Type)
Room_Room (ID_Room_Type, Number_Room)
How to place a new column Temp in the RoomType table that will take its value as the sum of the rooms from the Room_Room table.
This code does not work :
Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
Dim Db As New HotelEntities
Dim s = (From I In Db.Room_Type Select I.ID_Room_Type, I.Name_Room_Type, ColumnTemp = GetTotal_Room(I.ID_Room_Type)).ToList()
Me.DataGridView1.DataSource = s
End Sub
Private Function GetTotal_Room(id_room_type As Int32) As Int32
Dim Db As New HotelEntities
Return (From I In Db.Room_Room Where I.ID_Room_Type = id_room_type).Count
End Function
Message Error :LINQ to Entities does not recognize the method 'Int32
GetTotal_Room(Int32)' method, and this method cannot be translated
into a store expression.

I had a similar problem and I solved it by extracting the list first and then applying linq over it. You can try by altering your code as below.
Dim Db As New HotelEntities
Dim roomTypeList = Db.Room_Type.ToList()
Dim s = (From I In roomTypeList
Select I.ID_Room_Type, I.Name_Room_Type,
ColumnTemp = GetTotal_Room(I.ID_Room_Type)).ToList()
Me.DataGridView1.DataSource = s

Entity Framework will generate Linq query expressions to valid sql query.
As error message explain EF doesn't know how to convert your method GetTotal_Room to valid sql query.
Instead you can get required result from one query, without extra function.
From roomRoom In db.Room_Room
Join roomType In db.Room_Type On roomRoom.ID_Room_Type Equals roomType.ID_Room_Type
Select New With { roomRoom.ID_Room_Type, roomType.Name_Room_Type } Into roomtypes
Group roomtypes By roomtypes Into grouptypes
Select New With
{
Id = grouptypes.Key.ID_Room_Type,
Name = grouptypes.Key.Name_Room_Type,
Total = grouptypes.Count()
}
As additional notice, I don't know context of your application, but based on given sample, I think you can remove some prefixes and suffixes in table and column names
RoomType
Id
Name
Room
TypeId -- reference to RoomType.Id

Related

Unable to cast object error when attempting to return key/value pairs by querying a datacontext

I am attempting to get data from a datacontext. Normally, I've had no problems doing it, but I'm having trouble trying to return a list of key/value pairs.
Basically I'm attempting to grab all unique names from a table as the key column and the number of times they appear in the table as the value column.
My data would look like this:
apple 5
banana 1
dragonfruit 3
.
.
.
The full error message is:
Unable to cast object of type 'System.Data.Linq.DataQuery1[VB$AnonymousType_32[System.String,System.Int32]]' to type 'System.Collections.Generic.List`1
The code I'm using is this:
Dim indicators As List(Of Object)
Public Sub GetIndicatorData()
Using context = new A_DataContext
indicators = (From p In chartdata Group p By __groupByKey1__ = p.INDK8R Into g = Group
Select New With {.name = __groupByKey1__, .count = g.Count()}).AsEnumerable()
indDataSource = indicators
End Sub
but I've also tried to:
Return indicators as a list
Return indicators as an enumerable.
Use a class to encapsulate your anonymous type
Public Class NameAndCount
Public ReadOnly Property Name As String
Public ReadOnly Property Count as Integer
Public Sub New(name As String, count As Integer)
Me.Name = name
Me.Count = count
End Sub
End Class
' ...
Private indicators As IEnumerable(Of NameAndCount)
Public Sub GetIndicatorData()
Using context = new A_DataContext
indicators = From p In chartdata Group p By __groupByKey1__ = p.INDK8R Into g = Group
Select New NameAndCount(__groupByKey1__, g.Count())
indDataSource = indicators.ToList()
End Using
End Sub
Figured it out. I changed the declaration of indicators to simply be an object then removed the .enumerable (or .toList) from the query result.
Thank you for the consideration and time.

Grouping by multiple columns

I am not sure if the title is misleading but I wasn't sure how to summarise this one.
I have a table in an SQL DB where a record exists as below:
I would like to display the measurement values of this item in a gridview as below:
I thought about selecting the target values to a list (and the same for the actual values) as below:
Dim cdc As New InternalCalibrationDataContext
Dim allTargetvalues = (From i In cdc.int_calibration_records
Where i.calibration_no = Request.QueryString(0) And
i.calibration_date = Request.QueryString(1)
Select i.measure1_target, i.measure2_target, i.measure3_target).ToList()
Then joining the lists together in some way although I am unsure of how I could join the lists or even if this is the correct approach to be taking?
Well, let me first say that measure1_target, measure2_target, etc. is almost always indicative of bad database design. These should probably be in another table as the "many" end of a 1-to-many relationship with the table you posted. So to answer one of your questions: No, this is not the correct approach to be taking.
With the structure of your table in its current state, your best option is probably something like this:
Dim cdc As New InternalCalibrationDataContext
Dim allTargetValues As New List(Of Whatever)
For Each targetValue In (From i In cdc.int_calibration_records
Where i.calibration_no = Request.QueryString(0) AndAlso
i.calibration_date = Request.QueryString(1)
Select i)
allTargetValues.Add(New Whatever With {.MeasureNumber = 1,
.Target = targetValue.measure1_target,
.Actual = targetValue.measure1_actual })
allTargetValues.Add(New Whatever With {.MeasureNumber = 2,
.Target = targetValue.measure2_target,
.Actual = targetValue.measure2_actual })
allTargetValues.Add(New Whatever With {.MeasureNumber = 3,
.Target = targetValue.measure3_target,
.Actual = targetValue.measure3_actual })
Next
The Whatever class would look like this:
Public Class Whatever
Public Property MeasureNumber As Integer
Public Property Target As Integer
Public Property Actual As Integer
End Class

Get SQL single value from query as String

I have the following code in my code behind:
Dim name As String
name.text= Staff.LoadName(StaffID)
The following query in my Class:
Public Function LoadName(ByVal ID As String)
Dim ds As New DataSet
Dim SQL As String = ""
SQL="select name from Staff where StaffID='" & ID & "' "
ds = Common.QueryDataByDataset(SQL)
ds.Tostring()
Return ds
End Function
But the name.Text doesn't show the value. How to I get the single value and convert it to string to display? Thanks
I am guessing the Common.QueryDataByDataset is from your library or some third party. Assuming it is executing the query and populating the dataset, you should be able to change the last two lines of the LoadName function to this:
String name = ds.Tables.Item("Staff").Rows(0)("name").ToString()
return name
You should add error handling in this method. For example, check to make sure the query returns exactly one result. Also, this method appears to be susceptible to SQL injection: http://en.wikipedia.org/wiki/SQL_injection

vb.net syntax for order by clause in linq to sql that has select new with

I have a LINQ to sql statement that joins 2 tables. I would like to add a order by clause on one of the columns. However the order by clause does not seem to take effect at all.
Could you please suggest the right syntax in VB.net to achieve order by in the following:
Dim query = From dtIt In dbsomecontext.mytable
Join dtIl In dbsomecontext.anothertable On dtIt.ItemID Equals dtIl.ItemID
Where dtIl.IsAvailable = True
Order By dtIt.manufacturer
Select New With {
.Alpha = UCase((dtIt.manufacturer).Substring(0, 1))
}
Dim dtManufacturer As DataTable = csLINQOperations.LINQToDataTable(query)
Return dtManufacturer
Have you put a break point on the line where to Dim dtManufacturer ?
I created some sample classes to repersent your data objects as you've defined it.
Dim linqQuery = From dtIT In myTables _
Join dtIL In otherTables On dtIT.ItemID Equals dtIL.ItemID _
Where dtIL.IsAvaliable = True _
Order By dtIT.Manufacturer Ascending _
Select New With {.Alpha = UCase((dtIT.Manufacturer).Substring(0, 1))}
Now, when I have a break point on the line after this LINQ Query I can inspect the object linqQuery by using "linqQuery.ToList" and see the order of the data. It does infact order the output in an ordered fashion, based on the Manufacturer name.
Why is it that you think your code is not ordering the data? Using the Break Points and Watch, inspect your "query" object (using "query.ToList" in the Quick Watch) and see if the results are ordered correctly.
Yes, I figured the results were not ordered by "QuickWatch"ing dtManufacturer in the line :
Dim dtManufacturer As DataTable = csLINQOperations.LINQToDataTable(query)
Now, I have changed the query to as follows and it works :
Dim query = From dtIt In dbinkAndToner.InkAndToners
Join dtIl In dbinkAndToner.ItemsLists On dtIt.ItemID Equals dtIl.ItemID
Where dtIl.IsAvailable = True
Select New With {
.Alpha = ((dtIt.Manufacturer).Substring(0, 1))
}
Distinct
query = From dtIt In query
Order By dtIt.Alpha
Dim dtManufacturer As DataTable = csLINQOperations.LINQToDataTable(query)
Return dtManufacturer

How do I append a 'where' clause using VB.NET and LINQ?

I am pretty new to VB.NET and am having a bit of trouble here with something I thought should be simple.
Keeping it simple, let's say I have a Document table with "Name" that I want to search on (in reality there are several other tables, joins, etc. ..). I need to be able to build the query using a where clause based on string values passed in.
Example - the user may pass in "ABC", "ABC DEF", "ABC DEF GHI".
The final query would be (the syntax is not correct, I know):
Select * from Documents Where Name Like %ABC% AND Name Like %DEF% AND Name like %GHI%
So, I thought I could do something like this.
Dim query = From document In _context.Documents
<< loop based on number of strings passed in >>
query = query.Where( ... what goes here?? )
For some reason, being brain-dead or something, I can't figure out how to make this work in VB.NET, or if I'm doing it correctly.
I believe this is how you would do it in VB (I'm a C# developer):
query = query.Where(Function(s) s = "ABC")
See LINQ - Sample Queries for some examples.
I think the tricky part here is the unknown number of query parameters. You can use the underlying LINQ IQueryable(Of T) here to help.
I think the following would work (it's not compiled, just notepad code here):
Public Function GetDocuments(criteria as String)
Dim splitCriteria = SplitTheCriteria(criteria)
dim query = from document in _context.Documents
For Each item in splitCriteria
Dim localItem = item
query = AddCriteriaToQuery(query, localItem)
Next
dim matchingDocuments = query.ToList()
End Function
Private Function AddCriteriaToQuery(query as IQueryable(Of Document), criteria as string) as IQueryable(Of Document)
return query.Where(Function(doc) doc.Name = criteria)
End Function
Since LINQ will delay-execute the query you can append where clauses onto your query in the loop and then call .ToList() at the end to execute the query.
In LINQ to SQL you can add WHERE clauses to your query using the .Where method of the query object, as you noted in your question. To use the LIKE operator, try using the .Contains method of the object you're querying in the Lambda expression of your call to the Where method.
Here's a simplified example in a console application. Hopefully it will lead you in the correct direction.
Public Class Doc
Private _docName As String
Public Property DocName() As String
Get
Return _docName
End Get
Set(ByVal value As String)
_docName = value
End Set
End Property
Public Sub New(ByVal newDocName As String)
_docName = newDocName
End Sub
End Class
Sub Main()
Dim Documents As New List(Of Doc)
Documents.Add(New Doc("ABC"))
Documents.Add(New Doc("DEF"))
Documents.Add(New Doc("GHI"))
Documents.Add(New Doc("ABC DEF"))
Documents.Add(New Doc("DEF GHI"))
Documents.Add(New Doc("GHI LMN"))
Dim qry = From docs In Documents
qry = qry.Where(Function(d) d.DocName.Contains("GHI"))
Dim qryResults As List(Of Doc) = qry.ToList()
For Each d As Doc In qryResults
Console.WriteLine(d.DocName)
Next
End Sub
Note the .Contains("GHI") call in the Lambda expression of the .Where method. I'm referencing the parameter of the expression, "d", which exposes the DocName property, which further exposes the .Contains method. This should produce the LIKE query you're expecting.
This method is additive, i.e. the call to the .Where method could be enclosed in a loop to make additional LIKE operators added to the WHERE clause of your query.
Dim query = From document In _context.Documents where document.name = 'xpto' select document
Or
Dim query = From document In _context.Documents where document.name.contains('xpto') select document
If you do this in a loop, you can do something like this:
.Where(Function(i as mytype) i.myfiltervar = WhatIWantToSelect)