简体   繁体   English

如何将 Oracle 数据库 NUMBER 映射到 .NET Core 中的 c# bool 类型?

[英]How to map Oracle database NUMBER to c# bool type in .NET Core?

I have Oracle database table with column of type NUMBER.我有一个包含 NUMBER 类型列的 Oracle 数据库表。 Due to legacy reasons this column represents boolean such that value 0 represents false and value -1 represents true.由于遗留原因,此列表示布尔值,因此值 0 表示 false,值 -1 表示 true。

I need to map this table to the C# class and thus map this column to bool property with the specified mapping values.我需要将此表映射到 C# 类,从而将此列映射到具有指定映射值的 bool 属性。 I am using linq2db as ORM in a .NET Core applications (console and asp.net).我在 .NET Core 应用程序(控制台和 asp.net)中使用 linq2db 作为 ORM。 Is there a way to tell Oracle Managed Client (Oracle.ManagedDataAccess.Core) to automatically perform this mapping for all database queries I perform from my code?有没有办法告诉 Oracle Managed Client (Oracle.ManagedDataAccess.Core) 自动为我从我的代码执行的所有数据库查询执行此映射?

If you're using Fluent API to configure your models, from EF Core 2.1 onwards, you can use Value Conversions .如果您使用 Fluent API 配置您的模型,从 EF Core 2.1 开始,您可以使用Value Conversions

At this time there isn't a Built-in converter for NumberToBool but it can be written this way:目前没有内置的 NumberToBool 转换器,但可以这样写:

var converter = new ValueConverter<bool, int>(
    v => v ? -1 : 0,
    v => (v == -1));

entity.Property(e => e.IsNew)
    .HasColumnName("ISNEW")
    .HasConversion(converter);

The model in Net library has classes. Net 库中的模型具有类。 You would need to edit or override the class and add code below您需要编辑或覆盖类并在下面添加代码

    public class MyTable
    {
        private Boolean myBool { get; set; }

        public int OracleNumber
        {
            get { return (myBool == false) ? 0 : -1; }
            set { myBool = (value == -1) ? myBool = true : myBool = false; }
        }
    }

You need to configure mappings between System.boolean and "number" types in your mapping schema您需要在映射模式中配置 System.boolean 和“数字”类型之间的映射

// converter to query parameter
ms.SetConverter<bool, DataParameter>(val => new DataParameter { Value = <convert to number> });
// converter to query literal
ms.SetValueToSqlConverter(typeof(bool), (sb,tp,v) =>
{
    if (v is bool val) sb.Append(<number literal>);
    else               sb.Append("NULL");
});
// converter from db value to boolean
ms.SetConverter<int, bool>(val => val != 0);

Also probably you want to configure it only for columns, marked with "number" DbType, so use configuration overloads, that take dbtype as from/to type parameter.您也可能只想为标有“数字”DbType 的列配置它,因此使用配置重载,将 dbtype 作为 from/to type 参数。

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

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