Asp.net core利用dynamic簡化數據庫訪問

今天寫瞭一個數據庫的幫助類,代碼如下。 

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簡化數據庫訪問的文章就介紹到這瞭。希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: