当前位置 : 主页 > 网络编程 > ASP >

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

来源:互联网 收集:自由互联 发布时间:2023-01-30
今天写了一个数据库的帮助类,代码如下。 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)] =

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

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简化数据库访问的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持易盾网络。

上一篇:.net中的Span&lt;T&gt;类和Memory&lt;T&gt;类介绍
下一篇:没有了
网友评论