Linq to SQL外键 [英] Linq to SQL Foreign Keys
问题描述
用于数据库表的DDL:
DDL for Database Tables:
Users:
id - int - identity
name - varchar - unique
PCs:
id - int - idnetity
name - varchar - unique
userid - FK to Users
Apps:
id - int - identity
name - varchar
pcid - FK to PCs
我在Visual Studio 2008中使用Linq To SQL设计器创建了一个DataContext.
I created a DataContext using the Linq To SQL designer in Visual Studio 2008.
我要执行此查询:
select
users.name,
pcs.name,
apps.name
from
users u
join pcs p on p.userid = u.id
join apps a on a.pcid = p.id
在另一个线程中,我被告知我在其中发布了一个答案,指出以下内容不正确,并创建了交叉联接.
I was told in another thread where I posted an answer that the following was incorrect and that it created a cross-join.
var query = from u in db.Users // gets all users
from p in u.PCs // gets all pcs for user
from a in p.Apps // gets all apps for pc
select new
{
username = u.Name,
pcname = p.Name,
appname = a.Name
};
当我执行此查询时,我得到正确的结果.在每个表中有两个记录的交叉联接应该返回8个记录,但是我的查询正确地返回了两个记录.
When I execute this query I get the correct results. A cross-join with two records in each table should return 8 records but my query correctly returns the two records.
我很幸运吗,还是那个人告诉我我错了吗?
Am I lucky, or is the person telling me that I'm wrong confused?
推荐答案
这将起作用.这是正常现象,因为第二个"from"查询个人计算机的用户组,第三个"from"询问个人计算机的应用程序组.而且我想这不会像T-Sql那样产生交叉联接,因为条件已经在外键和关联中定义了.
That will work. It's normal because the second "from" inquires in the PC's set of the users and the third "from", the Apps set of the pcs. And I guess that is not going generate a cross join as T-Sql, because the conditions are already defined in the foreign keys and associations.
但是我想这应该是您希望通过内部联接获得的语法;
But I guess this should be the syntactically you want by inner join;
var query = from u in db.Users
join p in db.PCs on p.UserId == u.Id
join a in db.Apps on a.PCId == p.Id
select new
{
username = u.Name,
pcname = p.Name,
appname = a.Name
};
这篇关于Linq to SQL外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!