简体   繁体   English

EF 4.1 / Linq-to-SQL:什么是更好的:使用Equals或==?

[英]EF 4.1 / Linq-to-SQL: What is better: using Equals or ==?

We're having a discussion about using Equals or == on an int comparison in a LINQ query. 我们正在讨论在LINQ查询中对int比较使用Equals== We're using EF4.1 Code First. 我们正在使用EF4.1 Code First。 What is better? 什么是更好的?

var query = context.Boodschappen
                   .Where(b => b.BoodschapID == id).FirstOrDefault();

or: 要么:

var query = context.Boodschappen
                   .Where(b => b.BoodschapID.Equals(id)).FirstOrDefault();

And why ? 为什么

For Linq To Sql, you want neither. 对于Linq To Sql,你不需要。 Instead, use Object.Equals: .Where(b => Object.Equals(b.BoodschapID, id) 相反,使用Object.Equals: .Where(b => Object.Equals(b.BoodschapID, id)

Why? 为什么? Because of a Bug in the SQL Generator if id happens to be a nullable uniqueidentifier. 由于SQL生成器中的一个Bug,如果id恰好是一个可空的uniqueidentifier。 If using b.BoodschapID.Equals(id) or b.BoodschapID == id and b.BoodschapID happens to be a nullable Guid, the generated SQL will not be WHERE BoodschapID IS NULL but rather WHERE BoodschapID = @p0 which will not return any results. 如果使用b.BoodschapID.Equals(id)或b.BoodschapID == id和b.BoodschapID恰好是一个可以为空的Guid,生成的SQL将不会是WHERE BoodschapID IS NULL而是WHERE BoodschapID = @p0这将不会返回任何结果。

I know for sure that EF used to have the same bug. 我确信EF曾经有同样的错误。 No idea if it's solved yet. 不知道它是否已经解决了。 You can find more details in this question , just be aware that some of the answers generate horrendous SQL. 您可以在此问题中找到更多详细信息,请注意,某些答案会产生可怕的SQL。

Apart from that, there is no difference between Equals and == in Linq To SQL that I'm aware of. 除此之外,我知道的Linq To SQL中的Equals和==之间没有区别。

I 'prefer' the former. 我更喜欢'前者'。 It works on nullable properties too. 它也适用于可空属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM