Reputation: 391
Ok, so here's an enum, right?
public enum BrandSafe : short
{
Yes = 1,
No = -1,
Unknown = 0
}
Underlying datatype of short, OK, so far so good.
Here is a table:
Now, here is a DTO class:
public class VurlRow
{
public long VurlRMXID { get; set; }
public string VurlString { get; set; }
public Enums.BrandSafe BrandSafe { get; set; }
}
Finally, here is a linq method:
List<VurlRow> vurls = (from vurl in m_Context.Vurls
select new VurlRow()
{
BrandSafe = (Enums.BrandSafe)vurl.BrandSafe,
VurlRMXID = vurl.VurlRMXID,
VurlString = vurl.VurlString
}).ToList();
I've also tried (Enums.BrandSafe)Enum.ToObject(typeof(Enums.BrandSafe), vurl.BrandSafe) to produce the Enum. When I remove the line BrandSafe = (Enums.BrandSafe)vurl.BrandSafe, the call works, but with the line I get a InvalidCast exception.
"Specified cast is not valid."
Seems like it should be totally valid to me, but what do I know, not enough about enums and linq apparently, can anyone here help?
Upvotes: 1
Views: 214
Reputation: 1062915
BrandSafe
is tinyint
in the database; tinyint
maps to byte
, not short
. That's the problem. Make it:
public enum BrandSafe : byte
{
Yes = 1,
No = -1, // <====== see below
Unknown = 0
}
(short
would map to smallint
)
However!!!! Note that -1
is not really a legal value for either of byte
/tinyint
- it will be 255 or an OverflowException
in .NET (depending on whether it is a checked or unchecked context), and an arithmetic-overflow (error 220) at the database.
I do, however, wonder whether bool?
(in C#) and bit null
(TSQL) would be a better match.
Upvotes: 3