I'm fairly new to LINQ (and SQL at that). When trying to query my SQL Database in C# "Supervisors" (which contains only one column "Names" made of nvarchar(50) variables, none of which are Null), supvName ends up being an empty list. If I don't cast it as a List, supvName is of typeSystem.Data.EnumerableRowCollection<string> if that helps.
public addNewEmp()
{
InitializeComponent();
using (TestDataSet db = new TestDataSet())
{
var supvName = (from n in db.Supervisors
select n.Names).ToList();
foreach (string n in supvName)
{
supv_cbox.Items.Add(n);
}
}
}
Even when using a Where statement, that one result doesn't show up, so I'm sure it's something simple in my code that I just can't seem to figure out. I've already tried using AsEnumerable() which didn't change anything.
EDIT: I'm doing this in VS 2010 WPF. Also when I Preview Data in TestDataSet.xsd, it does return the all the data in the Database.
Solution: The problem was when I used a DataSet. When I used a DataContext instead it worked perfectly fine. Thanks to your DataSet or DataContext question lazyberezovsky or I never would have tried that.
Using the following works:
var supvName = db.Supervisors.Select(m => m.Names);
supv_cbox.ItemsSource = supvName;
Thanks Surjah Singh too.
When you are enumerating over DataTable with Linq to DataSet, you should call AsEnumerable() on datatable and use Field<T> extension to get column value:
var supvName = (from r in db.Supervisors.AsEnumerable()
select r.Field<string>("Names")).ToList();
BTW query variable r will be of DataRow type.
Your code can be simplified to:
var names = db.Supervisors.AsEnumerable().Select(r => r.Field<string>("Names"));
supv_cbox.DataSource = names.ToList();
//Var supvName = Supervisors.Select(m=>m.Names);
var supvName = from s in Supervisors.Tables[0].AsEnumerable()
select s.Field<string>("Names");
Related
String priceID = codeArray[0];
var priceResult = from PRICE_LIST in priceContext.PRICE_LIST
where PRICE_LIST.PRICE_ID == priceID
select new
{
PRICE_LIST.RETAIL,
PRICE_LIST.WHOLESALE
}.ToList();
I'm receiving a compile error that the anonymous type does not contain a definition for ToList() and I'm not sure why? I've seen many examples where queries are stored using this method. I can do priceResult.ToList(), but both the retail and wholesale price columns are in the same list element. So I can't get retail by selecting the first element ect. New to EF & LINQ and still on the learning curve.
You need to put the entire LINQ within parentheses like this:
var priceResult = (from PRICE_LIST in priceContext.PRICE_LIST
where PRICE_LIST.PRICE_ID == priceID
select new
{
PRICE_LIST.RETAIL,
PRICE_LIST.WHOLESALE
}).ToList();
otherwise it tries to make each new object to a list
The title is pretty self-explanitory, and it seems like it should be an easy task, but everything I've tried has not worked:
Here's my code, which works fine, but the table is variable, so I need to know the Columns it comes back with:
var data = db.Query("SELECT * FROM " + Table);
Here's a list of techniques I've tried:
data.GetType().GetProperties().ToList();
// prints 'Int32 Count' and 'System.Object Item [Int32]'
data.GetDynamicMemberNames()
// Error: '...IEnumerable<dynamic> does not have a definition for GetDynamicMemberNames'
// I also tried using System.Linq and System.Dynamic
I could also iterate through a loop, but there's got to be a more elegant way, right?
I'd like to end up with a List<String> of the Column Names.
List<String> cols = data.First().Columns;
It turns out the Columns Propery is an IList<string> type.
However, it is a property of an individual row of the data result (a row is a DynamicRecord data type), so it is unfortunately inaccessible from the result Object (data in my example). To access it, you need to get a single row, and .First() seems to be a pretty easy way to do that.
Here's my whole code in case anyone needs it:
WebMatrix.Data.Database db = new WebMatrix.Data.Database();
db.Open("ConnectionString");
var data = db.Query("SELECT * FROM " + Table);
List<String> cols = data.First().Columns;
I'm using linq to filling my datagrid view with this method:
public List<HopDongCungCap> XemHopDong()
{
return QL.HopDongCungCaps.ToList();
}
and this is my
Result
My dbo.HopDongCungCap just has 1-4 column
but i dont know why it appears the 5th column
Note that dbo.NhaCungCap has a relationship with dbo.HopDongCungCap
Thank you for watching my question!
A solution would be to project the wanted results with Linq like this:
var result = QL.HopDongCungCaps.Select(x => new
{
MaHD = x.MaHD,
TenHD = x.TenHD,
ThoiHan = x.ThoiHan,
NCC = x.NCC
}).ToList();
Note that I leave 'NhaCungCap' out from the result.
This will create a anonymous type.
But you can create a classobject or DTO(Dummy Transfer Object) and project the result that object. and assign that to the datagridview. (.Select(x=> new YourClassDTO...)
I am trying to sort some data from entity before passing them to another function. Both tableName and columnName are selected dynamically. This is what I'm doing:
string tableName = cboSelectTable.Text.ToString();
var comboBoxColumn = from a in Context.RULES where
a.ISCOMBOBOXCOLUMN == "Y" select a.COLUMN;
foreach (var colName in comboBoxColumn)
{
var getTableName = entityModel.GetType()
.GetProperty(tableName)
.GetValue(entityModel, null);
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.Select(colName)
.Distinct()
.OrderBy('"'+ colName +'"');
dgvCboColumn(getData, colName);
}
But this is not sorting the data. I also tried some other methods too, but couldn't figure it out. How can I resolve this?
I do not think that is the way, .OrderBy(...) works. Try ordering by an attribute:
SomeList.OrderBy(l => l.SomeAttribute);
I suspect ordering by a string results in each element being ordered by the same attribute, thus not ordering at all. In addition, I am not sure, if your where-clause works like that.
There is another relevant SO question already answered. You might want to have a look at it: click me!
You can simply place the Select after the OrderBy:
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.OrderBy(colName)
.Select(colName)
.Distinct();
This will allow you to reference the column name. (doesn't seem to work for some reason).
Alternatively, you can reference the current instance:
var getData = ((IQueryable<object>)getTableName)
.Where(colName + "!=null")
.Select(colName)
.Distinct()
.OrderBy("it");
Just getting my head around all this LINQ stuff and it seems I'm stuck at the first hurdle.
I have a datatable as such:
OrderNo LetterGroup Filepath
----------- ----------- --------------------------------------------------
0 0 Letters/SampleImage.jpg
0 0 Letters/UKPC7_0.jpg
0 0 Letters/UKPC8_0.jpg
What I need is to get all of the filepaths from the Filepath column into a String array. I thought LINQ would be perfect for this (am I right?), but can't seem to construct the correct query.
Can anyone provide some code samples that would point me in the right direction? I have searched around - but don't seem to be getting anywhere.
There are extension methods which make working with data sets much easier:
using System.Data.Linq;
var filePaths =
from row in dataTable.AsEnumerable()
select row.Field<string>("Filepath");
var filePathsArray = filePaths.ToArray();
You can also use the method syntax to put it in one statement:
var filePaths = dataTable
.AsEnumerable()
.Select(row => row.Field<string>("Filepath"))
.ToArray();
string[] filePaths = (from DataRow row in yourDataTable.Rows
select row["Filepath"].ToString()).ToArray();
If you want to use LINQ all the way, set up your database and create a context object. Then you should be able to do something like this:
var filepaths = from order in _context.Orders
select order.Filepath;
This is assuming your table for the row is named Orders, which I guess by your first column name of order. If you wanted to return a set of the order numbers as well for using later to know where the file path came from you could do something like so:
var results = from order in _context.Orders
select new
{
order.OrderNo,
order.Filepath
}
This would give you a new anonymous type that contained both those values as properties.