LINQ 2 SQL是如何转化为TSQL [英] How linq 2 sql is translated to TSQL

查看:137
本文介绍了LINQ 2 SQL是如何转化为TSQL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎LINQ2SQL不知道如何构建TSQL当你变换LINQ2SQL对象为域对象与构造。如:

It seems Linq2sql doesn't know how to construct the TSQL while you transform linq2sql object into domain object with constructors. Such as:

from c in db.Companies
select new Company (c.ID, c.Name, c.Location).Where(x => x.Name =="Roy");



但是,使用可设置的属性时,这将是确定。

But when using settable attributes, it will be OK.

from c in db.Companies
select new Company { ID = c.ID, Name = c.Name, Location = c.Location }.Where(x => x.Name =="Roy");



我不想让这些属性是可设置的。我怎样才能做到这一点?和任何人可以思考LINQ的2 SQL是如何转化为TSQL提供食物? !在此先感谢

I don't want to allow those attributes to be settable. How can I achieve this? And can anybody provide food for thought on how linq 2 sql is translated into TSQL? Thanks in advance!

推荐答案

这可能与L2S解析表达式的方式做的事情 - 它可以解析初始化器表达的对象,但没有构造函数表达式。基本上,L2S的工作方式是解析LINQ表达式任何LINQ提供程序的方式做然后转换结果放入SQL。

It's probably to do with the way L2S parses the expressions - it can parse the object initialiser expression, but not the constructor expression. Basically, the way L2S works is to parse the linq expressions the way any LINQ provider does and then convert the result into SQL.

您可以通过将其转换为一个IEnumerable第一实现你愿意,因为那么你就可以自由使用 LINQ到对象。在这个例子中你给,这是小事,但让我们推广到一个更复杂的情况下子句:

You could achieve what you'd like by converting it into an IEnumerable first, as then you'll be free to use LINQ to Objects. In the example you gave this is trivial, but let's generalise to a case with a more complex where clause:

var companyData =
    from c in db.Companies
    where c.Name.StartsWith("Roy")
    select new { c.ID, c.Name, c.Location };

var companies =
    from c in companyData.AsEnumerable()
    select new Company(c.ID, c.Name, c.Location);

这篇关于LINQ 2 SQL是如何转化为TSQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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