今天写了一个数据库的帮助类,代码如下。
public static class DbEx
{
public static dynamic ReadToObject(this IDataReader reader)
{
var obj = new DbObject();
for (int i = 0; i _values[index];
set => _values[index] = value;
}
}
public class DbField
{
public object DbData { get; set; }
public T Value()
{
return (T)Convert.ChangeType(DbData, typeof(T));
}
public static implicit operator string(DbField data) => data.Value();
public static implicit operator int(DbField data) => data.Value();
public static implicit operator DateTime(DbField data) => data.Value();
public static implicit operator double(DbField data) => data.Value();
public static implicit operator bool(DbField data) => data.Value();
}
}
简单的来讲,可以把如下代码
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简化数据库访问的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。