开发者

Using a LINQ Where clause to filter by data in an associated table

开发者 https://www.devze.com 2023-03-11 04:40 出处:网络
I have two tables, Articles and Statuses that I have associated in a ctx.dbml file. Articles id:int title:varchar(255)

I have two tables, Articles and Statuses that I have associated in a ctx.dbml file.

Articles
id:int
title:varchar(255)
status_id:int

Statuses
id:int
name:varchar(255)

What I'd like to do is filter all of the articles of a certain status. Hypothetically speaking, something like:

var filteredArticles = from article in ctx.Articles
                       where article.Status.name == "Active"
                       select article;

The issue tha开发者_如何学JAVAt I'm having is that in the above linq query, second line, Intellisense never gives me article.Status.name. I've seen code on the internet like this, so I must be missing something. Please help.


To do it like you want, you have to set up an association between the two tables.

How to: Create an Association (Relationship) Between LINQ to SQL Classes (O/R Designer)

Alternatively, you can just write the join manually.

var activeArticles = from a in ctx.Articles
                     join s in ctx.statuses on a.status_id equals s.id
                     select a;

If you go the association route, be very careful that you don't commit the SELECT N + 1 error.

0

精彩评论

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

关注公众号