简体   繁体   中英

LINQ - EF - FROM or JOIN

I use c#, linq and EF4.

I have two 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

I need query Entity Framework to retrive a list of Categories for a selected Content not associated in the Junction table.

At the moment I use this code (note the two FROM):

var categories = from category in context.CmsCategories
                 from content in category.CmsContents
                 select category;

That Returns a list of all category not associated in the entire database and not to a specific Content.

I need show the list of Categories not associates with a SPECIFIC Content

  • Any idea how to do it?
  • May I do it with JOIN? (EF does not map directly he Pure Junction Table)

Could you please write me the LINQ query so I can have a clear picture. Thanks fro your help.

You could try:

CmsCategories.Except(myContent.CmsCategories)

myContent is an instance of CmsContent, assuming you retrieved it before and you have lazy loading enabled.

Edit: a possible sample of code:

var myContent = context.CmsContents.FirstOrDefault(c => c.Id == 1);
var contentCategories = myContent.CmsCategories;
var otherCategories = context.CmsCategories.Except(contentCategories);
foreach (var item in otherCategories)
{
//whatever you need to do
}

I think you want to select from the CmsCategories and exclude anything that is in the associative table.

var query =
            context
                .CmsCategories
                .Except(context.CmsRelatedCategories.Select(x=>x.CmsCategory));

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