Linq how to write JOIN

Linq to EF, I am using asp.net 4, EF 4 and C #.

Here are two ways I came up with to request my data. Paths A and C work fine. B, however, it is necessary to implement an additional WHERE operator (like "where c.ModeContent ==" NA ").

My question is:

  • As for this type of join (e.g., outer join), what is the best approach to performance?
  • Could you show me some code to implement the optional WHERE statement in B?
  • Any way to improve this code?

Thank you for your time!: -)

// A var queryContents = from c in context.CmsContents where c.ModeContent == "NA" && !(from o in context.CmsContentsAssignedToes select o.ContentId) .Contains(c.ContentId) select c; // B - I need to implent where c.ModeContent == "NA" var result01 = from c in context.CmsContents join d in context.CmsContentsAssignedToes on c.ContentId equals d.ContentId into g where !g.Any() select c; // C var result02 = context.CmsContents.Where(x => x.ModeContent == "NA").Where(item1 => context.CmsContentsAssignedToes.All(item2 => item1.ContentId != item2.ContentId)); 
+4
source share
2 answers

As for query B, you can apply the condition as follows:

 var result01 = from c in context.CmsContents where c.ModeContent == "NA" join d in context.CmsContentsAssignedToes on c.ContentId equals d.ContentId into g where !g.Any() select c; 
+3
source

Your request will be far more readable and maintainable (and at least fulfilled) if you use your association properties instead of join :

 var result = from c in context.CmsContents where c.ModeContent == "NA" && !c.AssignedToes.Any() select c; 

I assume that navigating from CmsContent to CmsContentsAssignedToes is called AssignedToes . Change the name in my query if it really caused something else.

This query can be read aloud, and you know exactly what that means. join you should think about.

+3
source

Source: https://habr.com/ru/post/1342801/


All Articles