在Linq查询中比较byte [] [英] Comparing byte[] in Linq query
问题描述
我的SQL表中有一个二进制列,并且我使用以下C#代码成功查询了该表:
I have a binary column in my SQL table and I successfully query this table with the following C# code:
var hash = "http://www.whatever.com".ToSHA256HashBytes();
var landingPage = context.LandingPages.FirstOrDefault(lp => lp.UrlHash == hash);
- 请注意:"ToSHA256HashBytes"是我编写的扩展方法,它返回一个字节[]
这很好用,因为SQL会比较byte []的内容并返回匹配的"UrlHash"记录.
This works great because SQL will compare the content of the byte[] and return the record with matching "UrlHash".
但是,这在我的单元测试中不起作用,因为比较是在内存中执行的,并且字节[]的比较规则显然是不同的.如果两个字节数组在内存中的相同位置,而不是通过比较数组的内容,似乎C#会将两个字节数组视为相等.
however, this doesn't work in my unit test because the comparison is performed in memory and the rules to compare byte[] are, evidently, different. It seems like C# will deem two byte array to be equal if they are at the same location in memory and not by comparing the content of the arrays.
这意味着以下单元测试将失败
This means that the following unit test will fail
var data = new[]
{
new LandingPage() { UrlHash = "http://www.whatever.com".ToSHA256HashBytes() },
new LandingPage() { UrlHash = "http://mycompany.com/another/folder/page.php"".ToSHA256HashBytes() },
new LandingPage() { UrlHash = "http://someothercompany.com/folder/somepage.html"".ToSHA256HashBytes() }
};
var mockData = new Mock<DbSet<T>>();
var queryableData = data.AsQueryable();
mockData.As<IQueryable<T>>().Setup(m => m.Provider).Returns(queryableData.Provider);
mockData.As<IQueryable<T>>().Setup(m => m.Expression).Returns(queryableData.Expression);
mockData.As<IQueryable<T>>().Setup(m => m.ElementType).Returns(queryableData.ElementType);
mockData.As<IQueryable<T>>().Setup(m => m.GetEnumerator()).Returns(queryableData.GetEnumerator());
var mockContext = new Mock<MyContext>();
mockContext.Setup(m => m.LandingPages).Returns(mockData.Object);
var hash = "http://www.whatever.com".ToSHA256HashBytes();
var landingPage = mockContext.Object.LandingPages.FirstOrDefault(lp => lp.UrlHash == hash);
Assert.IsNotNull(landingPage);
有没有一种方法可以编写我的Linq查询,使其在单元测试以及查询数据库时都能正常工作?
Is there a way I can write my Linq query so that it works when unit testing as well as when querying the database?
I found a very similar question but the OP solved his problem by changing his query (which is unfortunately not an option for me) instead of actually finding a solution to his original problem.
推荐答案
You can use the Enumerable.SequenceEqual
extension method:
var landingPage = context.LandingPages
.FirstOrDefault(lp => lp.UrlHash.SequenceEqual(hash));
当且仅当两个源序列的长度相等,并且根据其类型的默认相等比较器,其对应元素相等时,SequenceEqual
的返回值才是true
.
The return value of SequenceEqual
is true
if and only if the two source sequences are of equal length and their corresponding elements are equal according to the default equality comparer for their type.
这篇关于在Linq查询中比较byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!