Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c# - Create a class that will hold a LINQ query?

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

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

            }
   }

The error is InvalidOperationException Class.

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();
        }

The error, 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?)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...