简体   繁体   English

C#Linq-SQL查询结果不返回任何内容

[英]C# Linq-SQL query result returning nothing

I'm fairly new to LINQ (and SQL at that). 我对LINQ(和SQL)很陌生。 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. 当尝试在C#“ Supervisors”(其中仅包含由nvarchar(50)变量组成的一列“ Names”,都不是Null )中查询我的SQL数据库时,supvName最终为空列表。 If I don't cast it as a List, supvName is of type System.Data.EnumerableRowCollection<string> if that helps. 如果我不将其supvName为列表,则如果有帮助, supvName的类型为System.Data.EnumerableRowCollection<string>

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. 即使使用Where语句,该结果也不会显示,因此我确定这只是我的代码中似乎无法弄清楚的简单事情。 I've already tried using AsEnumerable() which didn't change anything. 我已经尝试过使用AsEnumerable() ,它没有改变任何东西。

EDIT: I'm doing this in VS 2010 WPF. 编辑:我正在VS 2010 WPF中执行此操作。 Also when I Preview Data in TestDataSet.xsd, it does return the all the data in the Database. 同样,当我在TestDataSet.xsd中预览数据时,它会返回数据库中的所有数据。

Solution: The problem was when I used a DataSet. 解决方案:问题是当我使用数据集时。 When I used a DataContext instead it worked perfectly fine. 当我使用DataContext时,它工作得很好。 Thanks to your DataSet or DataContext question lazyberezovsky or I never would have tried that. 感谢您的DataSet或DataContext问题lazyberezovsky,否则我永远也不会尝试过。 Using the following works: 使用以下作品:

var supvName = db.Supervisors.Select(m => m.Names);
supv_cbox.ItemsSource = supvName;

Thanks Surjah Singh too. 还要感谢Surjah Singh。

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: 当使用Linq到DataSet枚举DataTable时,应在datatable上调用AsEnumerable()并使用Field<T>扩展名获取列值:

 var supvName = (from r in db.Supervisors.AsEnumerable()
                 select r.Field<string>("Names")).ToList();

BTW query variable r will be of DataRow type. BTW查询变量r将为DataRow类型。


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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM