开发者

Simple Query in LINQ

I have 3 tables. Basically, I have this structure:

Customer
--------
IDCustomer
NameCustomer

Product  
«««««««  
IDProduct  
NameProduct

Order  
«««««  
IDCustomer  开发者_高级运维
IDProduct

How to get a result like this, using LINQ:

Result  
««««««  
NameCustomer  
NameProduct

Thanks in advance!


Assuming you don't have proper relationships set up in the database (or you haven't generated navigation properties for your relationships), you could do the following:

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 }

It would be much easier, though, to add the proper foreign keys to the database and allow Entity Framework (or LINQ to SQL) generate the navigation properties for you. If that were the case, it would be as easy as:

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


The whole beauty of LINQ is that this should be all automatically done for you with automatically generated objects.

Make sure your table relationships are setup in SQL Server before moving them to your DBML file. After this, your Customer table will have Orders attached to it, in which your Products will be attached to your orders.

Such as selecting from your customer table (LINQ) will give you a list of Customers, in which will have an IENumerable list of Order objects attached to each.


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}

you can use linqpad.exe to test your linq query directly against your database

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜