Why does this LinQ query not like chars?

2019-07-17 15:23发布

问题:

I have a LINQ query that grabs all the data it needs and consolidates it into a data transfer object, everything works fine EXCEPT it throws query exceptions when I set one of the DTO's members (which is a char) to a char value...

An unhandled exception of type 'System.ServiceModel.FaultException' occurred in mscorlib.dll

Unable to create a constant value of type 'System.Char'. Only primitive types or enumeration types are supported in this context.

See the simplified query below:

var result = (from c in db.Foster_Carers
              where c.foster_carer_id == id
              join fc in db.Individual_Carers on c.first_carer_id equals fc.individual_carer_id
              select new FosterCarerPersonalInfoDTO
              {
                  carer_title = fc.title,
                  carer_forenames = fc.forename,
                  carer_surname = fc.surname,                                
                  carer_gender = 'm'
              }).SingleOrDefault();

Setting the gender to 'm' just won't work, syntactically it is okay, just not when the query is executed! What could be the issue?

回答1:

This is a limitation of EF because char is not a primitive type, see this answer for more details as to why. The limitation itself is also documented.

I would suggest you just use string.



回答2:

I've come across the same and had to store an intermediate value and do a conversion outside of the Linq query:

var intermediateResult = (from c in db.Foster_Carers
          where c.foster_carer_id == id
          join fc in db.Individual_Carers on c.first_carer_id equals fc.individual_carer_id
          select new 
          {
              oldResult = new FosterCarerPersonalInfoDTO
              {
                  carer_title = fc.title,
                  carer_forenames = fc.forename,
                  carer_surname = fc.surname,                                
              }
          ,   forConversion = new
              {
                  carer_gender = "m"
              }
          }).SingleOrDefault();

intermediateResult.oldResult.carer_gender = intermediateResult.forConversion.carer_gender[0];

var result = intermediateResult.oldResult;