0

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.

3
  • 3
    TestDataSet is a DataSet or DataContext? Commented Sep 17, 2013 at 14:08
  • TestDataSet is a DataSet Commented Sep 17, 2013 at 14:26
  • Then my solution below should work for you Commented Sep 17, 2013 at 14:28

2 Answers 2

1

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately supvName is still Count = 0 (tried both ways of implementing it). Could the problem possible be that I'm doing this in WPF instead of WinForm (I substituted DataSource out for DataContext and ItemsSource since i wasn't sure which)?
Recreated the window in WinForm and same issue XD Going to try using SQL commands and then DataContext to see if that works
0
    //Var supvName = Supervisors.Select(m=>m.Names);

   var supvName = from s in Supervisors.Tables[0].AsEnumerable()
                     select s.Field<string>("Names");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.