Asp.netcore利用dynamic简化数据库访问

2022-11-13 11:11:46 数据库 利用 简化

今天写了一个数据库的帮助类,代码如下。 

public static class DbEx
{
    public static dynamic ReadToObject(this IDataReader reader)
    {
        var obj = new DbObject();

        for (int i = 0; i < reader.FieldCount; i++)
        {
            obj[reader.GetName(i)] = new DbField()
            {
                DbData = reader[i]
            };
        }

        return obj;
    }

    public class DbObject : DynamicObject
    {
        //自己实现一个,不用ExpandoObject, 以支持无视大小写读取
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = this[binder.Name];
            return true;
        }

        Dictionary<string, object> _values = new Dictionary<string, object>(StrinGComparer.CurrentCultureIgnoreCase);

        public object this[string index]
        {
            get => _values[index];
            set => _values[index] = value;
        }
    }

    public class DbField
    {
        public object DbData { get; set; }

        public T Value<T>()
        {
            return (T)Convert.ChangeType(DbData, typeof(T));
        }

        public static implicit operator string(DbField data) => data.Value<string>();
        public static implicit operator int(DbField data) => data.Value<int>();
        public static implicit operator DateTime(DbField data) => data.Value<DateTime>();
        public static implicit operator double(DbField data) => data.Value<double>();
        public static implicit operator bool(DbField data) => data.Value<bool>();
    }
}

简单的来讲,可以把如下代码

GpsData parse(IDataReader reader)
{
    return new GpsData()
    {
        IsValid = (bool)reader["IsValid"],
        Location = new Location ()
        {
            Lon = (double)reader["Lon"],
            Lat = (double)reader["Lat"],
        },
        Angle = (double)reader["Angle"],
        Speed = (double)reader["Speed"]),
        UpdateTime = (double)reader["Speed"]),
    };
}

转换为如下形式

GpsData parse(IDataReader reader)
{
    var obj = reader.ReadToObject();
    var state = new GpsData()
    {
        IsValid = obj.IsValid,
        Location = new Location()
        {
            Lon = obj.Lon,
            Lat = obj.Lat,
        },
        Angle = obj.Angle,
        Speed = obj.Speed,
        UpdateTime = obj.UpdateTime,
    };
    return state;
}

到此这篇关于ASP.net core利用dynamic简化数据库访问的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

相关文章