I am having some problems using the OrderBy extension method in a LINQ query when it works with an enum type. I created a regular DataContext using visual studio, just dragging and dropping everything onto the constructor. Then I created separate entity models that are just POCO, and I used the repository template to retrieve data from my database and map it to my own entity models (or rather, I have a repository template that is created and IQueryable that will do all this) .
Everything works fine, except when I try to apply OrderBy (outside the repository) for the property that I mapped from short / smallint to an enumeration.
Here are the relevant code bits:
public class Campaign { public long Id { get; set; } public string Name { get; set; } .... public CampaignStatus Status { get; set; } ... } public enum CampaignStatus : short { Active, Inactive, Todo, Hidden } public class SqlCampaignRepository : ICampaignRepository { ... public IQueryable<Campaign> Campaigns() { DataContext db = new DataContext(); return from c in db.Campaigns select new Campaign { Id = c.Id, Name = c.Name, ... Status = (CampaignStatus)c.Status, ... }; } }
And then elsewhere
SqlCampaignRepository rep = new SqlCampaignRepository(); var query = rep.Campaigns().OrderBy(c => c.Status);
This raises the following exception: System.ArgumentException was not handled by user code Message = “Argument value” was incorrect. Expected “IQMedia.Models.CampaignType.” Actual “System.Int16.” Source = “System.Data.Linq” Trace stack : ved System.Data.Linq.SqlClient.SqlOrderExpression.set_Expression (SqlExpression value) ved System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitSelect (select SqlSelect) ved System.Data.Linq.SqlClient.SqlVisitor.is ) ved System.Data.Linq.SqlClient.SqlBinder.Visitor.VisitIncludeScope (SqlIncludeScope area) ...
(sorry for Danish there, ved = by / at).
I tried typecasting Status in short in the orderBy expression, but that doesn’t help, just as if I also applied it to the actual type of the enum.
Any help correcting this is greatly appreciated!
enums c # linq-to-sql
kastermester
source share