C# 实体框架和 VARBINARY
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/605790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity framework and VARBINARY
提问by Marcus L
I'm using the .NET entity framework and I've got one entity containing a varbinary. Is there an easy way to get the size of the varbinary in the codebehind, efter it's been retrieved from the database?
我正在使用 .NET 实体框架,并且我有一个包含 varbinary 的实体。是否有一种简单的方法可以在代码隐藏中获取 varbinary 的大小,然后从数据库中检索到它?
I'm thinking there might be some way to get the size directly from the entity, something like entity.Context.Size – or do one need to handle it differently?
我在想可能有某种方法可以直接从实体中获取大小,例如 entity.Context.Size – 或者是否需要以不同的方式处理它?
采纳答案by bernhof
A varbinary
translates to a byte[]
field in Entity Framework, which means you can check the Lengthproperty of the array:
Avarbinary
转换为byte[]
实体框架中的字段,这意味着您可以检查数组的Length属性:
int fieldSize = entity.MyVarBinaryField.Length;
As mentioned by tster: In a LINQ to Entities query, you can call the DataLengthmethod of the SqlFunctionsclass, which will translate into a DATALENGTHfunction call in the generated SQL statement. This only works with SQL Server and Entity Framework 4 or later:
正如tster提到的:在 LINQ to Entities 查询中,您可以调用SqlFunctions类的DataLength方法,该方法将转换为生成的 SQL 语句中的DATALENGTH函数调用。这仅适用于 SQL Server 和实体框架 4 或更高版本:
int? fieldSize = repository.Entity
.Select(e => SqlFunctions.DataLength(e.MyVarBinaryField)).Single();
回答by Marcus L
I solved it by running another query, getting the DATALENGTH() of the cell. Not the smoothest way but it works.
我通过运行另一个查询来解决它,获取单元格的 DATALENGTH()。不是最顺畅的方式,但它有效。
I'm still interested in hearing if anyone can come up with an answer for this though.
我仍然有兴趣听到是否有人可以为此提出答案。
回答by tster
I know this question is old, but EF now supports this by using SqlFunctions.DataLength()
我知道这个问题很旧,但是 EF 现在通过使用来支持这个 SqlFunctions.DataLength()