Data layer refactoring

Posted by Joey on Stack Overflow See other posts from Stack Overflow or by Joey
Published on 2012-12-18T10:31:45Z Indexed on 2012/12/18 11:03 UTC
Read the original article Hit count: 214

Filed under:
|

I've taken control of some entity framework code and am looking to refactor it. Before I do, I'd like to check my thoughts are correct and I'm not missing the entity-framework way of doing things.

Example 1 - Subquery vs Join

Here we have a one-to-many between As and Bs. Apart from the code below being hard to read, is it also inefficient?

from a in dataContext.As
where ((from b in dataContext.Bs
        where b.Text.StartsWith(searchText)
        select b.AId).Distinct()).Contains(a.Id)
select a

Would it be better, for example, to use the join and do something like this?

from a in dataContext.As
where a.Bs.Any(b => b.Text.StartsWith(searchText))
select a

Example 2 - Explicit Joins vs Navigation

Here we have a one-to-many between As and Bs and a one-to-many between Bs and Cs.

from a in dataContext.As
join b in dataContext.Bs on b.AId equals a.Id
join c in dataContext.Cs on c.BId equals b.Id
where c.SomeValue equals searchValue
select a

Is there a good reason to use explicit joins rather than navigating through the data model? For example:

from a in dataContext.As
where a.Bs.Any(b => b.Cs.Any(c => c.SomeValue == searchValue)
select a

© Stack Overflow or respective owner

Related posts about c#

Related posts about entity-framework