实用技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > ASP.NET > 实用技巧 > 利用dynamic简化数据库访问

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

作者:天方

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

您可能感兴趣的文章:
阅读全文