简体   繁体   中英

outer Join in linq with lambda expression

I have 2 tables ProfileType(profilename), Role(roldId,minSecurityLevel) and many to many relationship between this as roleProfiles(roleid,profilename,securityLevel)

I want to select all profileTypes and security levels for that profileType to particular role.

If roleProfile does not contain the entry for profiletype it will show null.

Can anyone help me for linq query using only lambda expression?

I am using repository Pattern

        var roleprofiles =  Repository.Query<Model.RoleProfile>()
            .Select(
                r =>
                new RoleProfileModel
                {
                    SecurityLevel = r.SecurityLevel,
                    ProfileCode = r.ProfileType.Code
                })
            .ToArray();

I want the result for left join on profileTypes

lambda version

  var roleprofiles =  Repository.Query<Model.RoleProfile>()
           .GroupJoin(Repository.Query<Model.ProfileType>(),
                      rp=>rp.Id, pt=>pt.TheRPId, // the the fields the tables are joined on  
            (rp,pt)   =>  new RoleProfileModel
            {
                SecurityLevel = rp.SecurityLevel,
                ProfileCode = rp.ProfileType.Code,
                XYZ         = pt.somethingFromProfType 
            })
        .ToList();   // to array ??? to List is better 
var details= (from p in repository.Query<Model.ProfileType>()
             join r in repository.Query<Model.RoleProfile>() on p.Id equals r.ProfileTypeId into g
             from x in g.DefaultIfEmpty()
             select new RoleProfileModel{
                    ProfileType=p.Name,
                    SecurityLevel=x==null?string.Empty:x.SecurityLevel,
                    ProfileCode=x==null?string.Empty:x.Code,
}).ToArray();

hope it will help you

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