My database schema uses varchar as default. With an EF(6) code first approach, I made sure my model is correct by setting the ColumnType for strings to varchar: modelBuilder.Properties<string>().Configure(p => p.HasColumnType("varchar"));
I'm using a PredicateBuilder to build my where clause and all works as expected; LINQ creates a parameterized query with the varchar datatype. I have also tried without the PredicateBuilder: the exact same issue arrises.
But once I add a Select statement, suddenly LINQ decides to change the datatype to nvarchar with no reason that I can think of. This of course has a seriously negative impact on my query, as sql server now has to do a bunch of implicit converts, rendering my indexes useless. It's now scanning the table instead of seeking.
var ciPredicate = PredicateBuilder.New<InfoEntity>(true);
ciPredicate = ciPredicate.And(x => x.InfoCode == ciCode);
ciPredicate = ciPredicate.And(x => x.Source == source);
//varchar - N'@p__linq__0 varchar(8000),@p__linq__1 varchar(8000)'
var ciQuery2 = this.Scope.Set<InfoEntity>().Where(ciPredicate).ToList();
//varchar - N'@p__linq__0 varchar(8000),@p__linq__1 varchar(8000)'
var ciQuery3 = this.Scope.Set<InfoEntity>().Where(ciPredicate).GroupBy(x => new { x.Source, x.InfoKey }).ToList();
//varchar - N'@p__linq__0 varchar(8000),@p__linq__1 varchar(8000)'
var ciQuery4 = this.Scope.Set<InfoEntity>().Where(ciPredicate).GroupBy(x => new { x.Source, x.InfoKey }).ToList().Select(group => group
.OrderByDescending(x => x.InfoSeqNr)
.FirstOrDefault()
);
//nvarchar - N'@p__linq__0 nvarchar(4000),@p__linq__1 nvarchar(4000)'
var ciQueryNvarchar = this.Scope.Set<InfoEntity>().Where(ciPredicate).GroupBy(x => new { x.Source, x.InfoKey })
.Select(group => group
.OrderByDescending(x => x.InfoSeqNr)
.FirstOrDefault()
).ToList();
table definition:
CREATE TABLE Info(
Id int NOT NULL,
InfoKey int NOT NULL,
Source varchar(50) NOT NULL,
InfoCode varchar(50) NOT NULL,
InfoDesc varchar(4000) NOT NULL,
InfoSeqNr int NOT NULL
)
Since this is just the start of a query we can not use ciQuery4 with the ToList() in between.
I can't for the life of me figure out why this is happening, any help would be greatly appreciated.
