19 October, 2012
0 Comments
1 category
If you do a left join in LINQ on multiple columns / properties. The types and names of these properties must be the same else you will get the error:
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to ‘GroupJoin’.
The following code generates the error, because the property [Company] is not the exact same as the property [Comp].
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Xunit.Assert; namespace Research.Rli.Tests { public class Person1 { public string Name { get; set; } public string Company { get; set; } } public class Person2 { public string Name { get; set; } public string Comp { get; set; } } [TestClass] public class ResearchTester { [TestMethod] public void Should_join_person1_and_person2() { var p1List = new List<Person1> { new Person1 { Company = "MyCompany", Name = "John Do"} }; var p2List = new List<Person2> { new Person2 { Comp = "MyCompany", Name = "John Do"} }; var query = from p1 in p1List join p2 in p2List on new { p1.Company, p1.Name } equals new { p2.Comp, p2.Name } into p2g from p2g1 in p2g.DefaultIfEmpty(null) select p1; } } }
To fix this error add property names to the anonymous objects.
using System; using System.Collections.Generic; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Assert = Xunit.Assert; namespace Research.Rli.Tests { public class Person1 { public string Name { get; set; } public string Company { get; set; } } public class Person2 { public string Name { get; set; } public string Comp { get; set; } } [TestClass] public class ResearchTester { [TestMethod] public void Should_join_person1_and_person2() { var p1List = new List<Person1> { new Person1 { Company = "MyCompany", Name = "John Do"} }; var p2List = new List<Person2> { new Person2 { Comp = "MyCompany", Name = "John Do"} }; var query = from p1 in p1List join p2 in p2List on new { Company = p1.Company, Name = p1.Name }
equals new { Company = p2.Comp, Name = p2.Name } into p2g from p2g1 in p2g.DefaultIfEmpty(null) select p1; } } }
Tags: LINQ
Category: Uncategorized
public override string[] GetRolesForUser(string username)
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
return null;
}
//check cache
var cacheKey = string.Format(“{0}_role”, username);
if (HttpRuntime.Cache[cacheKey] != null)
{
return (string[])HttpRuntime.Cache[cacheKey];
}
string[] roles = new string[]{};
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
roles = (from a in dc.Roles
error in join claue that the type expression is invalid -> join b in dc.UserRoles on a.RoleID equals b.RoleID
join c in dc.Users on b.UserID equals c.UserID
where c.UserName.Equals(username)
select a.RoleName).ToArray();
if (roles.Count() > 0)
{
HttpRuntime.Cache.Insert(cacheKey, roles, null, DateTime.Now.AddMinutes(_cacheTimeoutInMinute), Cache.NoSlidingExpiration);
}
}
return roles;
}