与WCF一起使用时如何在linq中给别名 [英] How To give alias in linq when use with WCF
问题描述
我在WCF上使用LINQ
在.dbml文件中,我拖动了sql表,在IService1.cs文件中,我的代码是:
I am using LINQ with WCF
in the .dbml file I dragged the sql table, my code in IService1.cs file is:
[OperationContract]
List<ASX_D> ASX_D12(String tablename, String company);
我在Service1.svc.cs中的代码是
and my code in Service1.svc.cs is
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
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?
推荐答案
此代码应该有效:
This code should work:
var q = (from p in db.ASX_Ds
where p.ASX_D_name == company
select p;
return q.ToList();
不需要中间匿名类型,实际上不能将其强制转换为泛型中的返回类型,因此,您想要的类型别名对于像C#这样的强OO语言来说是不起眼的.
如果要限制字段,则应声明 DataContract [列表< T>.方法 [ ^ ]
即使您要发送所有数据,这种转换也是值得的,因为它将接口与对象模型和数据库实现分离开来,并允许服务的版本控制.
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.
这篇关于与WCF一起使用时如何在linq中给别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!