将 Linq To Sql Binary 字段设置为 null
尝试将 Binary 字段设置为 null 会出现 ArgumentNull 异常。 我可以将字段设置为空,就像这样 new Binary(new byte[] {});
但这不是 null,只是一个空列。有使用 LinqToSql 的解决方法吗?
Trying to set a Binary field to null gives me an ArgumentNull exception.
I can set the field to be empty like this new Binary(new byte[] {});
but that's not null just an empty column. Is there a workaround using LinqToSql ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你还有别的事要发生。我刚刚创建了一个小型示例表,其中包含 id(身份)、可为空的 varbinary(MAX)、不可为空的 varbinary(MAX) 和时间戳。使用以下代码可以正常工作,没有错误。
此代码正确抛出(并捕获) SQLException,而不是 ArgumentNullException。
您是否有可能有一个部分类实现,该实现具有针对引发 ArgumentNullException 的属性的 SendPropertyChanging 处理程序?
编辑:基于OP的评论。
请注意,您不能直接将 byte[] 类型的变量分配给 Binary,因为这会调用 隐式转换操作,隐式转换会抛出ArgumentNullException。您应该在尝试分配该值之前检查该值是否为 null,如果 byte[] 变量为 null,则简单地分配 null。对我来说,这似乎是奇怪的行为,我希望他们将来能改变它。 MSDN 文档表明未来版本中可能会发生一些更改。
You've got something else going on. I just created a small sample table with an id (identity), nullable varbinary(MAX), non-nullable varbinary(MAX), and timestamp. Using the following code works just fine with no errors.
Where as this code properly throws (and catches) a SQLException, not an ArgumentNullException.
Is it possible that you have a partial class implementation that has a SendPropertyChanging handler for the property that is throwing the ArgumentNullException?
EDIT: based on the OP's comment.
Note that you can't assign a variable of type byte[] to the Binary directly as that invokes the implicit conversion operation and the implicit conversion will throw an ArgumentNullException. You should check if the value is null before attempting to assign it and simply assign null if the byte[] variable is null. To me this seems like odd behavior and I would hope that they would change it in the future. The MSDN documentation indicates that some change may occur in future versions.
您确定该字段在数据库中可以为空吗? linq 数据模型是否相应更新?如果使用基于属性的映射,则
[Column(...)]
属性中应有一个CanBeNull=true
设置。Are you sure that the field is nullable in the database? Are the linq data model updated accordingly? If using attribute-based mapping there should be a
CanBeNull=true
setting in the[Column(...)]
attribute.@tvanfosson(作为获得更好的代码格式的答案发布)
是的,你是对的,发生了一些奇怪的事情,超出了我的 C# 知识范围。
from.ImageThumbnail 是 byte[]
to.ImageThumbnail 是二进制的,
使用 ?或者 ??运算符不起作用,如果我只使用 if else 它可以工作,很奇怪。我不明白为什么:-)
@tvanfosson (posted as an answer to get better formatting of the code)
Yes you are right, something strange is going on, something beyond my C# knowledge.
from.ImageThumbnail is byte[]
to.ImageThumbnail is Binary
Using the ? or ?? operators won't work, if I just use if else it works, weird. I don't see why :-)
您可以使用 ExecuteQuery() 方法来传递您自己的 SQL。
You could use the ExecuteQuery() method to pass your own SQL.