I am having some issues with trying to figure out the correct way, or syntax, to join/concatenate a series of "name" columns from a separate table into a query.
Currently I am testing in LINQpad using two queries; the first returns all the master data that I use for other background work, and the second is a user-friendly version that I bind to a DGV. The issue comes in when I try to join the Physicians names like I do for a separate combobox.
This is what I have thus far - while it does return the Physician's name, it will NOT return the name if the TITLE field is NULL on the Physicians table.
Dim query1 = (From demog In data_Demogs
From MedHist In data_Demog_MedHists.where(Function(a) demog.ID_Demog = a.ID_Demog).defaultifempty
From BGLAssay In data_Demog_BGLs.where(Function(a) demog.ID_Demog = a.ID_Demog).defaultifempty
Select
demog.ID_Demog,
demog.Last_Name,
demog.First_Name,
demog.ID_Demog_AKA,
demog.DOB,
demog.Gender,
demog.ST_Complete,
demog.LT_Complete,
demog.LT_Due_Date,
demog.ID_Physician,
demog.ID_Reason_For_Call,
demog.Intl_Patient,
demog.Mayo_Patient,
MedHist.ID_Disease_Group,
MedHist.ID_Disease_Type,
BGLAssay.ID_BGL_Assay)
Dim query2 = (From items In query1
From demogAKA In data_Demogs.Where(Function(a) items.ID_Demog = a.ID_Demog_AKA).defaultifempty
From DType In tbl_Disease_Types.Where(Function(a) items.ID_Disease_Type = a.ID_Disease_Type).defaultifempty
From DGroup In tbl_Disease_Groups.Where(Function(a) items.ID_Disease_Group = a.ID_Disease_Group).defaultifempty
From RFC In tbl_Reason_For_Calls.Where(Function(a) items.ID_Reason_For_Call = a.ID_Reason_For_Call).defaultifempty
From Phys In tbl_Physicians.Where(Function(a) items.ID_Physician = a.ID_Physician).defaultifempty
From Title In tbl_Titles.Where(Function(a) Phys.ID_Title = a.ID_Title).defaultifempty
Select
items.ID_Demog,
items.Last_Name,
items.First_Name,
AKA_Name = demogAKA.Last_Name + ", " + demogAKA.First_Name,
items.DOB,
items.Gender,
items.ST_Complete,
items.LT_Complete,
items.LT_Due_Date,
DType.Disease_Type_Abr,
DGroup.Disease_Group_Name,
RFC.Reason_For_Call,
items.ID_Physician,
Phys_Name = Phys.Last_Name + ", " + Phys.First_Name + ", " + Title.Title
).distinct
console.writeline(Query2)
This is the currently query I for a combobox that DOES bring back all names, joining those names even if a field is NULL.
Dim Phys = (From e In tbl_Physicians
Group Join f In tbl_Titles On e.ID_Title Equals f.ID_Title
Into Matched = Group
From m In Matched.DefaultIfEmpty()
Select e.ID_Physician,
e.Last_Name,
e.First_Name,
e.Middle_Initial,
m.Title
).ToArray().Select(Function(item) New With {
.ID = item.ID_Physician,
.Phys_Name = (String.Join(", ",
String.Join(",",
New String() {item.Last_Name, item.First_Name, item.Title}).Split(
New Char() {","}, System.StringSplitOptions.RemoveEmptyEntries)))
})
Console.writeline(Phys)
When I try to add a third query to return just the Physician's name, and join that to the final query, I get the following error:
Local sequence cannot be used in LINQ to SQL implementations of query operators except the Contains operator.
'Query 1 removed to save space
Dim PhysNames = (From e In tbl_Physicians
Group Join f In tbl_Titles On e.ID_Title Equals f.ID_Title
Into Matched = Group
From m In Matched.DefaultIfEmpty()
Select e.ID_Physician,
e.Last_Name,
e.First_Name,
e.Middle_Initial,
m.Title
).ToArray().Select(Function(item) New With {
.ID = item.ID_Physician,
.Phys_Name = (String.Join(", ",
String.Join(",",
New String() {item.Last_Name, item.First_Name, item.Title}).Split(
New Char() {","}, System.StringSplitOptions.RemoveEmptyEntries)))
})
Dim query2 = (From items In query1
From demogAKA In data_Demogs.Where(Function(a) items.ID_Demog = a.ID_Demog_AKA).defaultifempty
From DType In tbl_Disease_Types.Where(Function(a) items.ID_Disease_Type = a.ID_Disease_Type).defaultifempty
From DGroup In tbl_Disease_Groups.Where(Function(a) items.ID_Disease_Group = a.ID_Disease_Group).defaultifempty
From RFC In tbl_Reason_For_Calls.Where(Function(a) items.ID_Reason_For_Call = a.ID_Reason_For_Call).defaultifempty
From Phys In PhysNames.Where(Function(a) items.ID_Physician = a.ID).defaultifempty
Select
items.ID_Demog,
items.Last_Name,
items.First_Name,
AKA_Name = demogAKA.Last_Name + ", " + demogAKA.First_Name,
items.DOB,
items.Gender,
items.ST_Complete,
items.LT_Complete,
items.LT_Due_Date,
DType.Disease_Type_Abr,
DGroup.Disease_Group_Name,
RFC.Reason_For_Call,
items.ID_Physician,
Phys.Phys_Name
).distinct
console.writeline(Query2)
When I try to join my working query into the final query, I get the following error:
Invalid cast from 'System.String' to 'VB$AnonymousDelegate_0`2[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934...
'Query1 removed to save space
Dim query2 = (From items In query1
From demogAKA In data_Demogs.Where(Function(a) items.ID_Demog = a.ID_Demog_AKA).defaultifempty
From DType In tbl_Disease_Types.Where(Function(a) items.ID_Disease_Type = a.ID_Disease_Type).defaultifempty
From DGroup In tbl_Disease_Groups.Where(Function(a) items.ID_Disease_Group = a.ID_Disease_Group).defaultifempty
From RFC In tbl_Reason_For_Calls.Where(Function(a) items.ID_Reason_For_Call = a.ID_Reason_For_Call).defaultifempty
From Phys In tbl_Physicians
Where items.ID_Physician = Phys.ID_Physician
Group Join f In tbl_Titles On Phys.ID_Title Equals f.ID_Title
Into Matched = Group
From m In Matched.DefaultIfEmpty()
Select
items.ID_Demog,
items.Last_Name,
items.First_Name,
AKA_Name = demogAKA.Last_Name + ", " + demogAKA.First_Name,
items.DOB,
items.Gender,
items.ST_Complete,
items.LT_Complete,
items.LT_Due_Date,
DType.Disease_Type_Abr,
DGroup.Disease_Group_Name,
RFC.Reason_For_Call,
items.ID_Physician,
PhysName = Function(a) String.Join(", ",
String.Join(",",
New String() {Phys.Last_Name, Phys.First_Name, m.Title}).Split(
New Char() {","}, System.StringSplitOptions.RemoveEmptyEntries))
).distinct
console.writeline(Query2)
After a long time playing around in LINQpad, and then finally re-reading JM's answer to a former question I had, I realized what I was doing wrong.
As per his post:
The problem is that, while LINQ in general has no issue with that code, LINQ to Entities does. LINQ syntax is the same for every provider but the implementation under the hood differs and, in the case of LINQ to Entities, your LINQ code has to translated to SQL and, in this case, there's no mapping from String.Join to SQL. That code would work fine with LINQ to Objects so one solution is to push that operation out of the original query and into a LINQ to Objects query. That would mean selecting the raw data with your LINQ to Entities query, calling ToList or ToArray on the result to materialise the query, then performing another query on that result. That second query will be LINQ to Objects rather than LINQ to Entities and so String.Join will not be an issue.
So... Once I realized I needed to push out the String.Join, I ended up with the following code:
Dim DispList = (From items In MastList
From demogAKA In dbACL.data_Demog.Where(Function(a) items.ID_Demog = a.ID_Demog_AKA).DefaultIfEmpty
From DType In dbACL.tbl_Disease_Type.Where(Function(a) items.ID_Disease_Type = a.ID_Disease_Type).DefaultIfEmpty
From DGroup In dbACL.tbl_Disease_Group.Where(Function(a) items.ID_Disease_Group = a.ID_Disease_Group).DefaultIfEmpty
From RFC In dbACL.tbl_Reason_For_Call.Where(Function(a) items.ID_Reason_For_Call = a.ID_Reason_For_Call).DefaultIfEmpty
From e In dbACL.tbl_Physician.Where(Function(a) items.ID_Physician = a.ID_Physician).DefaultIfEmpty
Group Join f In dbACL.tbl_Title On e.ID_Title Equals f.ID_Title
Into Matched = Group
From m In Matched.DefaultIfEmpty()
Select
items.ID_Demog,
items.Last_Name,
items.First_Name,
AKALname = demogAKA.Last_Name,
AKAFname = demogAKA.First_Name,
items.DOB,
items.Gender,
items.ST_Complete,
items.LT_Complete,
items.LT_Due_Date,
DType.Disease_Type_Abr,
DGroup.Disease_Group_Name,
RFC.Reason_For_Call,
items.ID_Physician,
PLName = e.Last_Name,
PFname = e.First_Name,
PMI = e.Middle_Initial,
PTitle = m.Title
).Distinct.ToList().Select(Function(a) New With {
a.ID_Demog,
a.Last_Name,
a.First_Name,
.AKA_Name = (String.Join(", ",
String.Join(",",
New String() {a.AKALname, a.AKAFname}).Split(
New Char() {","}, System.StringSplitOptions.RemoveEmptyEntries))),
a.DOB,
a.Gender,
a.ST_Complete,
a.LT_Complete,
a.LT_Due_Date,
a.Disease_Type_Abr,
a.Disease_Group_Name,
a.Reason_For_Call,
a.ID_Physician,
.PName = (String.Join(", ",
String.Join(",",
New String() {a.PLName, a.PFname, a.PTitle}).Split(
New Char() {","}, System.StringSplitOptions.RemoveEmptyEntries)))
}).ToList()
I have in my table MS Access named ( Table1 ) two fields ( ID1 - Team1 ).
With NumericUpDown1 i select the number of rows that i want to display after randomize in DataGridView2.With NumericUpDown2 i select the number of columns that i want to display after randomize in DataGridView2.If i choose with NumericUpDown2 only one column ( the number 1 ) it work very well with this query :
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Con_randomize()
Dim rows As Integer
If Not Integer.TryParse(NumericUpDown1.Value, rows) Then
MsgBox("NUMBER NOT AVAILABLE", MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, "Error")
NumericUpDown1.Value = ""
NumericUpDown1.Focus()
Exit Sub
End If
If NumericUpDown2.Value = 1 Then
Dim sql As String = String.Format("SELECT Top {0} ID1,Team1 From Table1 ORDER BY RND(-(100000*ID1)*Time())", rows)
InfoCommand = New OleDbCommand(sql, Con_randomize)
InfoAdapter = New OleDbDataAdapter()
InfoAdapter.SelectCommand = InfoCommand
InfoTable = New DataTable()
InfoAdapter.Fill(InfoTable)
DataGridView2.DataSource = InfoTable
DataGridView2.Columns(0).HeaderText = "NUMERO"
DataGridView2.Columns(1).HeaderText = "CATEGORY1"
End If
End Sub
How to make if i choose with NumericUpDown2 the number 2 or 3 columns i want to display in Datagridview2.
The columns will be named ( CATEGORY2 - CATEGORY3 ) . for example ( 1 Victor - David - Vincent ) ( 2 wiliam- George - Joseph ) ..in my only field named Team1 I have a hundred of the names
I'm not 100% sure why you need a query to initialize the data, but give this a go. It will automatically create the columns the way you need them.
' If NumericUpDown2.Value = 1 Then ' Comment This If Block Out
' Create the Teams String
Dim teamsString as New System.Text.StringBuilder("")
For i as Integer = 1 to Convert.ToInt32(NumericUpDown2.Value)
teamsString.Append(", (SELECT Top 1 Team1 From Table1 ORDER BY RND(-(100000*ID1)*Time())) as Category" + i.ToString())
Next
Dim sql As String = String.Format("SELECT Top {0} ID1" + teamsString.ToString() + " From Table1 ORDER BY RND(-(100000*ID1)*Time())", rows)
InfoCommand = New OleDbCommand(sql, Con_randomize)
InfoAdapter = New OleDbDataAdapter()
InfoAdapter.SelectCommand = InfoCommand
InfoTable = New DataTable()
InfoAdapter.Fill(InfoTable)
DataGridView2.DataSource = InfoTable
DataGridView2.Columns(0).HeaderText = "NUMERO"
' Don't Need This, We Made It the Binding Name
' DataGridView2.Columns(1).HeaderText = "CATEGORY1"
I have three dropdowns; the second one (Members) populates based on what's in the first (Units), and the third one (Customers) SHOULD populate based on what's in the second; but it doesn't.
Here's the query that works in LINQPad (returns a list of Company names):
select distinct companyname from customers C left join members M on M.MemberNo = C.MemberNo where M.MemberNo = '052' order by companyname
...but does not work in the following code:
'Populate the Members dropdown
Dim selectedUnit As String = DropDownListUnits.Text
Dim membersDT As DataTable
sql = "select distinct shortname, M.memberno from members M left join memberunitproducts mup on M.MemberNo = mup.MemberNo where unit = '" + selectedUnit + "' order by shortname"
retDS = sqlDAL.runSQLDataSet(sql)
membersDT = retDS.Tables(0)
DropDownListMembers.DataSource = membersDT
DropDownListMembers.DataTextField = "shortname"
DropDownListMembers.DataValueField = "memberno"
DropDownListMembers.DataBind()
'Populate the Customers dropdown
Dim selectedMember As String = DropDownListMembers.DataValueField
Dim customersDT As DataTable
sql = "select distinct companyname from customers C left join members M on M.MemberNo = C.MemberNo where M.MemberNo = '" + selectedMember + "' order by companyname"
retDS = sqlDAL.runSQLDataSet(sql)
customersDT = retDS.Tables(0)
DropDownListCustomers.DataSource = customersDT
DropDownListCustomers.DataTextField = "companyname"
DropDownListCustomers.DataValueField = "companyname"
DropDownListCustomers.DataBind()
The third (Customers) dropdown remains unpopulated when this runs - why?
It's probably not needed, but here is the code for the first ("Units") dropdown:
'Populate the Units dropdown
Dim unitsDT As DataTable
sql = "Select distinct unit from masterunits where abs(active) = 1"
retDS = sqlDAL.runSQLDataSet(sql)
unitsDT = retDS.Tables(0)
DropDownListUnits.DataSource = unitsDT
DropDownListUnits.DataTextField = "unit"
DropDownListUnits.DataValueField = "unit"
DropDownListUnits.DataBind()
What am I missing or doing wrong?
I had to change this:
Dim selectedMember As String = DropDownListMembers.DataValueField
...to this:
Dim selectedMember As String = DropDownListMembers.SelectedItem.Value
I can use GetSchemaTable and GetXMLSchema to get information about field types, sizes etc. from a Foxpro DBF opened with VFPOLEDB but can not get any information pertaining to what indexes are in the tables/CDX.
I dont want to use the indexes, just the criteria on which the index is built to aid me in generating the SQL commands to create the tables on a SQL server and import the data.
I could do a DISPLAY STRUCTURE output to a text file on all of the tables and parse it in VB.NET but I am hoping there is something I am overlooking as I am not that familiar with VB.NET/OLEDB syntax yet.
Little bit of research given away these results. I have started with having a look at ForeignKey.FKTableSchema Property and unfortunately not a .NET property. Later on things looked good when I found OleDbSchemaGuid.Indexes Field and everything looked good until I ran the application and got the Method is not supported by this provider. Eventually the following article lit up the way,
GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Indexes - How to access included columns on index
and this finding
The OleDb and Odbc providers do not provide a built-in catalog method
that will return non-key ("Included") index columns.
However it was some really interesting suggestion which let to writing this little Console application for you to harvest the indexes available in the table. This is achieved by directly querying the schema table from SQL. The following example is on Employees table of famous Northwind sample database. Here you go,
//Open a connection to the SQL Server Northwind database.
var connectionString =
"Provider=SQLOLEDB;Data Source=SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;Encrypt=False;TrustServerCertificate=False";
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
var select = "SELECT " +
" T.name AS TABLE_NAME" +
" , IX.name AS INDEX_NAME" +
" , IC.index_column_id AS IX_COL_ID" +
" , C.name AS COLUMN_NAME" +
" , IC.is_included_column AS INCLUDED_NONKEY" +
" " +
"FROM " +
" sys.tables T " +
" INNER JOIN sys.indexes IX" +
" ON T.object_id = IX.object_id " +
" INNER JOIN sys.index_columns IC" +
" ON IX.object_id = IC.object_id " +
" AND IX.index_id = IC.index_id " +
" INNER JOIN sys.columns C" +
" ON IC.object_id = C.object_id " +
" AND IC.column_id = C.column_id " +
" " +
"WHERE T.name = 'Employees'" +
"ORDER BY IC.index_column_id";
OleDbCommand cmd = new OleDbCommand(#select, connection);
cmd.CommandType = CommandType.Text;
var outputTable = new DataSet("Table");
var my = new OleDbDataAdapter(cmd).Fill(outputTable);
foreach (DataTable table in outputTable.Tables)
{
foreach (DataRow myField in table.Rows)
{
//For each property of the field...
foreach (DataColumn myProperty in table.Columns)
{
//Display the field name and value.
Console.WriteLine(myProperty.ColumnName + " = " +
myField[myProperty].ToString());
}
Console.WriteLine();
}
}
}
Console.ReadLine();
and finally the results,
TABLE_NAME = Employees
INDEX_NAME = PK_Employees
IX_COL_ID = 1
COLUMN_NAME = EmployeeID
INCLUDED_NONKEY = False
TABLE_NAME = Employees
INDEX_NAME = LastName
IX_COL_ID = 1
COLUMN_NAME = LastName
INCLUDED_NONKEY = False
TABLE_NAME = Employees
INDEX_NAME = PostalCode
IX_COL_ID = 1
COLUMN_NAME = PostalCode
INCLUDED_NONKEY = False
However, later on by removing the restrictions I managed to get over the Method is not supported by this provider. error and ended up summing it up like this shorter solution,
//Open a connection to the SQL Server Northwind database.
var connectionString =
"Provider=SQLOLEDB;Data Source=SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;Encrypt=False;TrustServerCertificate=False";
using (OleDbConnection cnn = new OleDbConnection(connectionString))
{
cnn.Open();
DataTable schemaIndexess = cnn.GetSchema("Indexes",
new string[] {null, null, null});
DataTable schemaIndexes = cnn.GetOleDbSchemaTable(
OleDbSchemaGuid.Indexes,
new object[] {null, null, null});
foreach (DataRow myField in schemaIndexes.Rows)
{
//For each property of the field...
foreach (DataColumn myProperty in schemaIndexes.Columns)
{
//Display the field name and value.
Console.WriteLine(myProperty.ColumnName + " = " +
myField[myProperty].ToString());
}
Console.WriteLine();
}
Console.ReadLine();
}
Which results to a longer output to sort out but part of it would be
TABLE_CATALOG = Northwind
TABLE_SCHEMA = dbo
TABLE_NAME = Employees
INDEX_CATALOG = Northwind
INDEX_SCHEMA = dbo
INDEX_NAME = LastName
PRIMARY_KEY = False
UNIQUE = False
CLUSTERED = False
TYPE = 1
FILL_FACTOR = 0
INITIAL_SIZE =
NULLS =
SORT_BOOKMARKS = False
AUTO_UPDATE = True
NULL_COLLATION = 4
ORDINAL_POSITION = 1
COLUMN_NAME = LastName
COLUMN_GUID =
COLUMN_PROPID =
COLLATION = 1
CARDINALITY =
PAGES = 1
FILTER_CONDITION =
INTEGRATED = False
Perfect!
Everything I needed to extract. Since it was in vb.net section I posted my rough code, I filtered the fields returned so I could list a few here.
It returns all pertinent information relating to the indexes, even complex ones created with expressions.
All tables in the path provided in the Connection String with CDX indexes will be returned.
TABLE_NAME = schematest
INDEX_NAME = char3ascen
NULLS = 1
EXPRESSION = char3ascen
TABLE_NAME = schematest
INDEX_NAME = expressn
NULLS = 2
EXPRESSION = LEFT(char1null,4)+SUBSTR(char2,4,2)
TABLE_NAME = schematest
INDEX_NAME = multifld
NULLS = 2
EXPRESSION = char1null+char2
TABLE_NAME = customer
INDEX_NAME = zip
NULLS = 1
EXPRESSION = zip
Private Sub GetIndexInfo_Click(sender As Object, e As EventArgs) Handles GetIndexInfo.Click
Dim cnnOLEDB As New OleDbConnection
Dim SchemaTable As DataTable
Dim myField As DataRow
Dim myProperty As DataColumn
Dim ColumnNames As New List(Of String)
Dim strConnectionString = "Provider=vfpoledb;Data Source=D:\ACW\;Collating Sequence=general;DELETED=False"
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
ColumnNames.Add("TABLE_NAME")
columnnames.Add("INDEX_NAME")
columnnames.Add("NULLS")
columnnames.Add("TYPE")
columnnames.Add("EXPRESSION")
SchemaTable = cnnOLEDB.GetSchema("Indexes")
'For Each myProperty In SchemaTable.Columns
For Each myField In SchemaTable.Rows
For Each myProperty In SchemaTable.Columns
If ColumnNames.Contains(myProperty.ColumnName) Then
Console.WriteLine(myProperty.ColumnName & " = " & myField(myProperty).ToString)
End If
Next
Console.WriteLine()
Next
Console.ReadLine()
DGVSchema.DataSource = SchemaTable
End Sub
I am trying to perform this query on two DataTables in a DataSet
SELECT Totals.accCategory, Totals.ID, Totals.Account, Sum(Totals.Jan) AS Jan FROM (SELECT * FROM Allocated UNION SELECT * FROM Spent) AS Totals GROUP BY Totals.accCategory, Totals.ID, Totals.Account
As they are generated in code (in memory) into the DataSet I need to use LINQ thus:
Dim t = (From totals In (allocated.AsEnumerable.Union(spent.AsEnumerable)) _
Group totals By accCategory = totals.Item("accCategory"), ID = totals.Item("ID"), Account = totals.Item("Account") _
Into g = Group _
Select New With {Key .accCategory = accCategory, Key .ID = ID, Key .Account = Account, Key .Jan = g.Sum(Function(totals) Totals.Item("Jan"))}).ToList
Which fails as there are some instances where there are no records to sum. The Access query returns an empty cell - which is what I want. I can make the LINQ statement work by using If(IsDbNull(totals.Item("Jan")),0,totals.Item("Jan")) but then I get 0.00 if the total is zero (which is correct) but also if there are no items to sum (which I don't want)
I have tried Select New With {Key .accCategory = accCategory, Key .ID = ID, Key .Account = Account, Key .Jan = g.Sum(Function(totals) DirectCast(totals.Item("Jan"), Nullable(Of Decimal)))}).ToList which doesn't work either.
How can I make .Jan a Nullable(Of Decimal) and accept DBNull as a value??
Thanks
Andy
Got it!
Dim t = (From totals In (allocated.AsEnumerable.Union(spent.AsEnumerable)) _
Group totals By accCategory = totals.Item("accCategory"), ID = totals.Item("ID"), Account = totals.Item("Account") _
Into g = Group _
Select New With {Key .accCategory = accCategory, Key .ID = ID, Key .Account = Account, Key .Jan = If(g.AsQueryable.Any(Function(totals) totals.Field(Of Nullable(Of Decimal))("Jan").HasValue), g.AsQueryable.Sum(Function(totals) totals.Field(Of Nullable(Of Decimal))("Jan")), Nothing)}).ToList