【问题标题】:Get columns values in data table using linq from Entity Framework使用 Entity Framework 中的 linq 获取数据表中的列值
【发布时间】:2017-03-21 07:11:17
【问题描述】:

我是 LINQ 查询的新手,请帮助我找到解决方案。

我在 Entity Framework 数据模型中有一个源,有一个表 currency 绑定到源,列 currencyIDCurrencyName

我需要使用 LINQ 查询从数据库中获取值到 DataTable

我尝试了如下所述的方法,但它不起作用:

 var dataset = Source.T_Currency
    .Where(x=> x.CurrencyID == x.CurrencyID &&  x.CurrencySymbol == x.CurrencySymbol)
    .Select(x => new x.Currency
    {
        CurrencyID = x.CurrencyID,
        CurrencySymbol = x.CurrencySymbol
    }).ToList();

【问题讨论】:

    标签: c# entity-framework linq datatable


    【解决方案1】:

    如果您想从 T_Currency 中选择所有行,请尝试

    Source.T_Currency
        .Select(x => new
        {
            x.CurrencyID,
            x.CurrencySymbol
        })
        .ToList()
    

    要通过任何值过滤结果,请在 Select 之前添加 Where 语句:

    Source.T_Currency
        .Where(x => x.CurrencySymbol == myCurrency) // where myCurrency is variable/parameter
        .Select(x => new
        {
            x.CurrencyID,
            x.CurrencySymbol
        })
        .ToList()
    

    这是 Select 语句的示例,但实际上在这种情况下它不是必需的,因此 Source.T_Currency.ToLost() 返回与第一个代码 sn-p 相同的结果。区别在于值的类型,但如果你可以使用原始类,那么你不应该创建匿名类型。

    【讨论】:

    • 是的,我想将 T_Currency 中的所有行选择到数据表中。
    • ` DataTable table = new DataTable();使用 (var reader = ObjectReader.Create(t)) { table.Load(reader); }`
    【解决方案2】:

    你应该像这个例子一样使用 LINQ Join:

            var custSupJoin =
                from sup in suppliers
                join cust in customers on sup.Country equals cust.Country
                select new { Country = sup.Country, SupplierName = sup.SupplierName, CustomerName = cust.CompanyName };
    

    【讨论】:

      猜你喜欢
      • 2019-11-24
      • 1970-01-01
      • 2017-01-23
      • 1970-01-01
      • 2013-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多