开发者

LINQ Query that is able to identity a Row in a Junction Table with two variables - How to do it?

开发者 https://www.devze.com 2023-02-17 09:48 出处:网络
I use c#, linq and EF4. I need help to write a LINQ quer开发者_运维百科y that is able to identify a Row in a DataBase using two variables for a Composite PRIMARY KEY.

I use c#, linq and EF4.

I need help to write a LINQ quer开发者_运维百科y that is able to identify a Row in a DataBase using two variables for a Composite PRIMARY KEY.

Here tables in my DataBase represented in my Conceptual Model:

DataBase Tables:

CmsContents
CmsCategories
CmsRelatedCategories (Pure Juction Table)

Entity Type:

CmsContent
CmsCategory

Entyt Set:

CmsContents
CmsCategories

I have some Navigational Properties:

for CmsContents --> CmsCategories --> Return Collection of Cms CmsCategory
for CmsCategories --> CmsContents --> Return Collection of Cms CmsContents

Data in DataBase for the Junction Table is presented:

CategoryId     ContentId
7              1
7              2
9              2

I need to identify a SINGLE OBJECT in the Pure Junction Table using two variables CategoryId and ContentId example:

CategoryId     ContentId
9              2

At the moment I use this code to retrieve a single Object but does not work properly.

CmsContent myContentObj = (CmsContent)context.CmsContents.Where(x => x.ContentId == myContentId);

Any idea how to solve it?


Use this:

CmsContent myContentObj = context.CmsContents.Where(x => x.ContentId == myContentId).FirstOrDefault();

I assumed that ContentId is the complete primary key for the CmsContent table. This assumption should be correct, because otherwise your mapping table wouldn't make any sense.

Explanation:
Your query doesn't work, because where returns an IEnumerable<CmsContent>, not a single instance. That's what FirstOrDefault is for: It returns the first found element or null (more precisely default(CmsContent)), if no elements where found with the specified content id.

0

精彩评论

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