String.Equals()无法按照预期工作 [英] String.Equals() not working as intended

查看:124
本文介绍了String.Equals()无法按照预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用LINQ通过我的实体框架的一个表来搜索和查找基于名称的群。这个名字是一个字符串,似乎是统一code(说,这是在EDMX)。我有一个方法 GetGroup()和我通过在搜索的名称。调试通过code,我已经有一个在我的数据库名为test组。有一次,我通过一个名为TEST组中我希望它返回它已经在数据库中的测试。它由于某种原因,没有找到测试,认为TEST不存在。这里是我的查询,我不明白为什么它不工作。请帮助。

名称中的组名通过。我的 .Equals 似乎如果 gr.Name 和名称完全相同的只有工作。如果一个字符是大写在两个串中的一个,那么.Equals不起作用。我曾尝试使用 InvariantCultureIgnoreCase ,而且似乎并没有帮助。如果有人问,在 MyLeagueId LeagueId 总是匹配,数据库设置,以便可以有一组一个不同的联赛标识。我不认为这是问题。

  G组=(从GR在this.DatabaseConnection.Groups
           其中,gr.Name.Equals(姓名,StringComparison.OrdinalIgnoreCase)及&放大器;
           gr.LeagueId == this.MyLeagueId
           选择GR).FirstOrDefault();


解决方案

在使用LINQ到实体,它会自动将其转换为LINQ to SQL的。如果数据库中的字段你正在做一个.Equals没有NOCASE(在我的例子的SQLite)的整理,然后它永远是区分大小写的。在otherwords,数据库定义了如何做字符串比较,而不是code。

I am using LINQ to search through one of my Entity Framework tables and find a "group" based on the name. The name is a string and appears to be Unicode (says it is in the edmx). I have a method GetGroup() and I pass in a name to search for. Debugging through the code, I already have a group named "Test" in my database. Once I pass in a group named "TEST" I expect it to return the "Test" which was already in the database. It for some reason, does not find the "Test" and thinks "TEST" doesn't exist. Here is my query, I cannot see why it does not work. Please help.

"name" is the passed in the group name. My .Equals seems to only work if the gr.Name and name are the exact same. If one character is capital in one of the two strings, then the .Equals doesn't work. I have tried to use InvariantCultureIgnoreCase, and that did not seem to help. In case someone asks, the MyLeagueId and LeagueId will always match, the database is setup so there can be a group in a different league id. I do not think this is the problem.

Group g = (from gr in this.DatabaseConnection.Groups
           where gr.Name.Equals(name, StringComparison.OrdinalIgnoreCase) &&
           gr.LeagueId == this.MyLeagueId
           select gr).FirstOrDefault();

解决方案

When using LINQ to Entities, it will automatically convert it to LINQ to SQL. And if the database field you are doing a .Equals on does not have a collate of NOCASE (SQLite in my example) then it will always be case-sensitive. In otherwords, the database defines how to do the string comparison rather than code.

这篇关于String.Equals()无法按照预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆