这篇文章主要介绍“Asp.net core怎么利用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简化数据库访问”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。