简体   繁体   中英

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

I have Oracle database table with column of type NUMBER. Due to legacy reasons this column represents boolean such that value 0 represents false and value -1 represents true.

I need to map this table to the C# class and thus map this column to bool property with the specified mapping values. I am using linq2db as ORM in a .NET Core applications (console and asp.net). 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?

If you're using Fluent API to configure your models, from EF Core 2.1 onwards, you can use Value Conversions .

At this time there isn't a Built-in converter for NumberToBool but it can be written this way:

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. 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

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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