创建一个将容纳LINQ查询的类? [英] Create a class that will hold a LINQ query?

查看:63
本文介绍了创建一个将容纳LINQ查询的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该问题是该问题的继续,如何绑定具有多种类型的变量? LINQ

This question is a continuation of the this question, How to bind a variable with multiple types? LINQ

我试图选择一行包含30列的数据,条件是列Staff_No中的唯一值.该行具有几种数据类型.

I am trying to select a row of data that has 30 columns in it, the criteria is a unique value from the column Staff_No. The row has several data types.

我的语法不正确,这是代码.

I can't get the the syntax correct and this is the code.

internal class DatabaseQueries
   {
       public static IEnumerable<int> ModValues(DatabaseDataContext database, int staffNo)
            {
                return database.Staff_Mod_TBLs
                    .Where(staff => staff.Staff_No == staffNo).Cast<int>().ToList();

            }
   }

错误为这段代码给了我这个错误,

And this code gives me this error,

 public static IEnumerable<decimal> ModValues(DatabaseDataContext database, int staffNo)
        {
            return database.Staff_Mod_TBLs
                .Where(staff => staff.Staff_No == staffNo).Select(staff => staff.Days_No_D).ToList();
        }

错误Severity Code Description Project File Line Suppression State Error CS0266 Cannot implicitly convert type 'System.Collections.Generic.List<decimal?>' to 'System.Collections.Generic.IEnumerable<decimal>'. An explicit conversion exists (are you missing a cast?)

推荐答案

我正在尝试选择一行
[并在评论中...]
我试图获取具有几种数据类型的整行.

I am trying to select a row
[and in a comment...]
I was trying to get the whole row which has several data types.

然后,您不需要Cast()ToList().如果您想要一条记录,只需获取该条匹配记录:

Then you don't need to Cast() or ToList(). If you want a single record, just fetch that single matching record:

return database.Staff_Mod_TBLs
               .Single(staff => staff.Staff_No == staffNo);

或者,如果您想返回null而不是在没有匹配项时抛出错误:

or, if you want to return null instead of throwing an error when there's no match:

return database.Staff_Mod_TBLs
               .SingleOrDefault(staff => staff.Staff_No == staffNo)

然后,您当然需要更改方法的返回类型:

Then of course you'd need to change the method's return type:

public static Staff_Mod_TBL ModValues(...)

(假设类型名基于表名.如果不同,则根据需要替换.)

(Assuming the type name based on the table name. Substitute as needed if it's different.)

基本上,您要寻找的是代表该表中记录的对象的实例.不是列值的集合.

Basically, what you are looking for is an instance of the object which represents a record in that table. Not a collection of column values.

这篇关于创建一个将容纳LINQ查询的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆