简体   繁体   中英

subqueries in Linq to Sql

IM stuck in linq query where im searching database & showing result using

DBSearchDataContext db = new DBSearchDataContext();
        object q = from b in db.Products
                   where b.ProductCode.Contains(val) |
                   b.ProductName.Contains(val) |
                   b.Specification.Contains(val) |
                   b.Description.Contains(val) |                       
                   b.Category.Contains(val) 
                   select b;

      GridView1.DataSource = q;
     GridView1.DataBind();

i can not display category name from category table where categoryID matches.

I do this in sql like this

how to do this in linq

SELECT ID, ProductCode, DisplayOrder, ProductName, imgThumb, inStock, Status, Amount, (SELECT Category FROM Category AS aaa WHERE (Products.CategoryID = CategoryID)) AS Category FROM Products ORDER BY ID DESC

help me

If you are missing some mapping, why not use a simple join?

var q = from p in db.Products
        join c in db.Category on p.CategoryID equals c.CategoryID
        where ...
        select new
        {
          p.ProductCode,
          ...,
          c.Category
        };

or with proper mappings:

var q = from p in db.Products
        where ...
        select new
        {
          p.ProductCode,
          ...,
          p.Category.Category
        };

You can put the subquery into the Linq LET clause. See

for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM