Search code examples
entity-frameworklinqlinq-to-sql

Can I mix LINQ and Fluent Syntax in EF Core?


I have the following query which works just fine (inasmuch as it generates the proper SQL command):

var sites = from sm in this.context.SiteMemberships
    join s in this.context.Sites on sm.SiteUid equals s.SiteUid
    join sd in this.context.SiteData on s.SiteUid equals sd.SiteUid
    join p in this.context.Providers on s.ProviderUid equals p.ProviderUid
    join r in this.context.Regions on p.RegionUid equals r.RegionUid
    join o in this.context.Offices on s.OfficeUid equals o.OfficeUid
    join u in this.context.Users on sm.UserUid equals u.UserUid
    where 
        u.Email == userEmail ||
        EF.Functions.Like(s.Classification, "117400-74%")
    select new {
        s.Field1,
        sd.Field2,
        p.Field3
    };

As you can see, it's a complex query and trying to use the Fluent API is very cumbersome. However, I want the 'Where' clause to be programmable. Based on what features the current user has, they should be able to search on different criteria. A Level 1 support person can search only on an exact match of the Classification field, but a Level 2 support person can search on wildcards.

Is there any way to mix the syntax. What I want is something like this:

var (sites = from sm in this.context.SiteMemberships
    join s in this.context.Sites on sm.SiteUid equals s.SiteUid
    join sd in this.context.SiteData on s.SiteUid equals sd.SiteUid
    join p in this.context.Providers on s.ProviderUid equals p.ProviderUid
    join r in this.context.Regions on p.RegionUid equals r.RegionUid
    join o in this.context.Offices on s.OfficeUid equals o.OfficeUid
    join u in this.context.Users on sm.UserUid equals u.UserUid)
    .Where(g => this.GetSearchCriteria(g)) 
    .Select(g => g);

Solution

  • You need to add select new { s, sd, p, r, o, u } after your last join

    var sites = (from sm in this.context.SiteMemberships
        join s in this.context.Sites on sm.SiteUid equals s.SiteUid
        join sd in this.context.SiteData on s.SiteUid equals sd.SiteUid
        join p in this.context.Providers on s.ProviderUid equals p.ProviderUid
        join r in this.context.Regions on p.RegionUid equals r.RegionUid
        join o in this.context.Offices on s.OfficeUid equals o.OfficeUid
        join u in this.context.Users on sm.UserUid equals u.UserUid
        select new { s, sd, p, r, o, u })
        .Where(g => this.GetSearchCriteria(g)) 
        .Select(g => g);