LinqToSql InvalidCastException
好的,这是一个枚举,对吧?
public enum BrandSafe : short
{
Yes = 1,
No = -1,
Unknown = 0
}
底层数据类型是short,好的,到目前为止一切顺利。
这是一个表:
现在,这是一个 DTO 类:
public class VurlRow
{
public long VurlRMXID { get; set; }
public string VurlString { get; set; }
public Enums.BrandSafe BrandSafe { get; set; }
}
最后,这是一个 linq 方法:
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还尝试过 (Enums.BrandSafe)Enum.ToObject(typeof(Enums.BrandSafe), vurl.BrandSafe) 来生成 Enum。当我删除 BrandSafe = (Enums.BrandSafe)vurl.BrandSafe 行时,调用有效,但使用该行时我收到 InvalidCast 异常。
“指定的演员阵容无效。”
似乎它对我来说应该完全有效,但我知道什么,显然对枚举和 linq 还不够,这里有人可以帮忙吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
BrandSafe
在数据库中是tinyint
;tinyint
映射到byte
,而不是short
。这就是问题所在。使其:(short
将映射到smallint
)但是!!!!请注意,
-1
并不是byte
/tinyint
的任一的真正合法值 - 它将是 255 或.NET 中的 OverflowException(取决于它是已检查上下文还是未检查上下文)以及数据库中的算术溢出(错误 220)。不过,我确实想知道
bool?
(在 C# 中)和bit null
(TSQL) 是否是更好的匹配。BrandSafe
istinyint
in the database;tinyint
maps tobyte
, notshort
. That's the problem. Make it:(
short
would map tosmallint
)However!!!! Note that
-1
is not really a legal value for either ofbyte
/tinyint
- it will be 255 or anOverflowException
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#) andbit null
(TSQL) would be a better match.