Linq select projection int to enum to string to enumerated facet doing weird things

Mar 21, 2011 at 1:46 PM

Hi,

I'm having a strange problem taking an int, casting it as an enum and converting the enum to a string and then inserting it into a string element with enum facet restrictions on it.

I don't know if this has anything to do with Linq to Xsd but I'm posting it anyway.

This code here does not work:

 

var res = (from t in db.Statuses
           select new
           {
               Broken = ((BatchStatuses)t.Status).ToString(),
               Fixed = BatchStatus(t.Status),
           }).ToList();

private static string BatchStatus(int status)
{
    string output;

    output = ((BatchStatuses)status).ToString();

    return output;
}

 

For the status 3, Broken is set to the string "3".

For Fixed, which goes through the BatchStatus() method, 3 becomes "Posted"

In the real code,

 

((BatchStatuses)t.Status).ToString()

 

will fail because "3" is not in the enum list on the Xsd.

But this:

BatchStatus(t.Status)

Does work because the method returns "Posted"

Here's the call Exception details:

Xml.Schema.Linq.LinqToXsdException occurred
  Message="Failed to set value on the property \"VQ5ReplyStatus\". Possible reason: The Given Value (3) Violates Restrictions: Enumeration = (Editing Deleted Posted Exported Processed Inprogress)"
  Source="Xml.Schema.Linq"
  StackTrace:
       at Xml.Schema.Linq.XTypedElement.SetElementWithValidation(XName name, Object value, String propertyName, SimpleTypeValidator typeDef) in c:\programs\linqtoxsd\XObjects\Src\API\XObjectsSimpleType.cs:line 54
  InnerException: 

Anybody get this one?

Regards,

James.

Mar 22, 2011 at 3:12 PM

The enum in the xsds seems to only know about strings (Editing Deleted Posted Exported Processed Inprogress), so it will not accept the Integer value of your .NET enum, but only those types...

Mar 22, 2011 at 4:58 PM

I'm not passing in the integer value, the return from

BatchStatuses.Posted.ToString() 

is "3" in the broken code and "Posted" in the working code.
And I do mean string literal when I type "3", integer 3 is 3.

BatchStatus()

Always returns "Posted" so I'm using that in my Linq query.

I've either found a bug in NET3.5 or LinqToXsd.

I'm guessing it's a bug in NET3.5 though, as that's what executes ToString() and returns "3" instead of "Posted".

J.
Mar 24, 2011 at 9:14 AM

You are right.... Strange behaviour, I have never seen that before..