ODP.NET / EF6 - CHAR datatype in WHERE clause

白昼怎懂夜的黑 提交于 2019-12-10 18:55:35

问题


I'm starting a project with EF6 and ODP.NET and I'm having trouble performing look-ups based on fixed-length CHAR columns.

The following code returns no results, even though this user exists in the database.

using (var context = new Entities())
 {
   var search = "testuser";
   var result = context.Users
                .Where(u => u.UserName == search)
                .FirstOrDefault();
  }

I know I can get around this by padding the search string or by trimming the database column, but I'm looking for an alternate solution.

I noticed that if I execute the query directly using OracleConnection/OracleCommand, then it works. Is there an attribute or anything I can add to the entity class to cause ODP.NET to bind the variable as an OracleDbType.Char?

Basically, I'm looking for a way to reproduce the following behavior from EF6:

var cmd = new OracleCommand("SELECT * FROM users WHERE user_name = :p0", conn);
cmd.Parameters.Add(":p0", OracleDbType.Char).Value = "testuser";

I also tested with Devart's dotConnect Oracle driver. Using that driver, I can do a look-up successfully by adding the following line of code. I would prefer to use ODP.NET over dotConnect, though. It seems ODP.NET is ignoring this property because it has no effect when using ODP.NET. Is there an equivalent to this that ODP.NET will recognize?

modelBuilder.Entity<Users>()
            .Property(u => u.UserName
            .IsFixedLength();

If I could, I would just change the column type to VARCHAR2 and wash my hands of this, but unfortunately, that is not an option at the moment. Any help you can provide would be very much appreciated!


回答1:


replace the Oracle command with

SELECT * FROM users WHERE cast(user_name as varchar2(20)) = :p0

You can use CAST to convert most datatypes to most other datatypes in Oracle. A CHAR datatype is nasty to work with (it's deprecated for a reason) and converting it to varchar2(xx) is the best option.



来源:https://stackoverflow.com/questions/28244561/odp-net-ef6-char-datatype-in-where-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!