LINQ中的简单查询

时间:2011-04-13 14:08:32

标签: sql linq

我有3张桌子。基本上,我有这个结构:

Customer
--------
IDCustomer
NameCustomer

Product  
«««««««  
IDProduct  
NameProduct

Order  
«««««  
IDCustomer  
IDProduct

如何使用LINQ:

得到这样的结果
Result  
««««««  
NameCustomer  
NameProduct

提前致谢!

3 个答案:

答案 0 :(得分:4)

假设您没有在数据库中设置正确的关系(或者您没有为关系生成导航属性),您可以执行以下操作:

var result = from c in _context.Customer
             join o in _context.Order on c.IDCustomer equals o.IDCustomer
             join p in _context.Product on o.IDProduct equals p.IDProduct
             select new { c.NameCustomer, p.NameProduct }

但是,将正确的外键添加到数据库并允许Entity Framework(或LINQ to SQL)为您生成导航属性会更容易。如果是这样的话,那将很容易:

var result = _context.Order.Select(o => new 
    { 
        o.Customer.NameCustomer,
        o.Product.NameProduct
    });

答案 1 :(得分:2)

LINQ的全部之处在于,应该使用自动生成的对象自动执行此操作。

在将表关系移动到DBML文件之前,请确保在SQL Server中设置了表关系。在此之后,您的客户表将附有订单,您的产品将附加到您的订单。

例如从您的客户表(LINQ)中进行选择将为您提供一个客户列表,其中将包含附加到每个客户的IENumerable Order对象列表。

答案 2 :(得分:0)

from t1 in Product
join t2 in Order on t1.IDProduct equals t2.IDProduct
join t3 in Customer on t2.IDCustomer equals t3.IDCustomer
select new { t1.NameProduct, t3.NameCustomer}

您可以使用linqpad.exe直接针对您的数据库测试您的linq查询