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
171 views
in Technique[技术] by (71.8m points)

asp.net - linq to sql using select new inside class file

I usually use linq to sql with an IQueryable or IEnumerable to get data like this:

    public static IQueryable getSomething() 
    {
        var getit = from d in database.table select d;

        return getit;
    }

and it works fine but i am trying to use select new with it like this:

    public static IQueryable getSomething() 
    {
       var getit = from d in database.table select new 
       { 
          value1 = d.1,
          value2 = d.2
       };

    return getit;
}

this is a sample code and not the actual code.

but that wont work, how do i do this?

thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You cannot type any method in C# to be the explicit type of an anonymous types. They cannot be "named" so to speak and hence cannot appear in metadata signatures.

https://stackoverflow.com/a/1070564/971839

First, You need to create a class like,

public class MyClass
    {

        public string Property1{get;set;}
        public string Property2{ get; set; }
    }

Then Replace Your Method with,

public static IEnumerable<MyClass> getSomething() 
        {
           var getit = from d in database.table select new 
          MyClass  { 
              Property1 = d.1,
              Property2 = d.2
                   };

        return getit;
    }

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

...