Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
3.75/5 (4 votes)
See more:
I am using LINQ with WCF
in the .dbml file I dragged the sql table, my code in IService1.cs file is:

XML
[OperationContract]
List<ASX_D> ASX_D12(String tablename, String company);


and my code in Service1.svc.cs is

XML
public List<ASX_D> ASX_D12(string tablename, string company)
{
    var q = (from p in db.ASX_Ds
            where p.ASX_D_name == company
            select new      
    {
      qq=p.ASX_D_close ,
      ff=p.ASX_D_date,
      ss=p.ASX_D_exchange,
      oo=p.ASX_D_high,
      gg=p.ASX_D_low,
      fg=p.ASX_D_name,
      dfgdfg=p.ASX_D_open
      qweqwe=p.ASX_D_sector,
      cvbcvb=p.ASX_D_symbol,
      aedasew=p.ASX_D_time,
      sdfsdf=p.ASX_D_type,ruwoeru=p.ASX_D_volume
   });
   return q.ToList();


but it give the error


XML
Cannot implicitly convert type 'System.Collections.Generic.List<AnonymousType#2>' to 'System.Collections.Generic.List<SilverlightProjectwithWCF.Web.ASX_D>' C:\Documents and Settings\hgtech\Desktop\SilverlightProjectwithWCF\SilverlightProjectwithWCF.Web\Service1.svc.cs    134 20  SilverlightProjectwithWCF.Web




How we can give an alias to columns in a LINQ query?
Posted
Updated 27-Apr-11 2:38am
v4
Comments
Keith Barrow 27-Apr-11 8:39am    
I improved the English a little and formatted the code for you.
Bruno Tagliapietra 27-Apr-11 8:52am    
linq is c# not sql, you have no aliases. If your method return type is List<TypeName> you must return a list of TypeName, not a list of anonymous type. So in your select you should do something like "... select new ASX_D{ PublicProperty1 = value1, publicField = value2, }" ... ...

1 solution

This code should work:

C#
var q = (from p in db.ASX_Ds
         where p.ASX_D_name == company
          select p;
return q.ToList();


The intermediate anonymous type is not required, in fact it can't be cast to the return type in the generic, so the type aliasing you want is a non-starter in a strongly OO language like C#.

If you want to restrict the fields you should declare a DataContract[^]with the fields you want and convert, you can write convertor method and an call
q.ToList().ConvertAll<datacontracttype>(ConversionFunction);

See List<T>.ConvertAll<TOutput> Method [^]

Such conversion is worthwhile even if you want to send all the data as it de-couples your interface from your object model and database implementation and allows versioning of the service.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900