下載app免費(fèi)領(lǐng)取會(huì)員
網(wǎng)友投稿
更多目的將book表中的id,name,price 映射到Book類中的Id1,Name1,Price1
class Program
{
static SQLiteConnection conn;
static string dbStr = "test.db";
static void Main(string[] args)
{
SqlMapper.SetTypeMap(typeof(Book), new CustomTypeMap<Book>());//定義映射規(guī)則
SQLiteConnection.CreateFile(dbStr);
conn = new SQLiteConnection($"Data Source={dbStr};Version=3;");
string sql = "create table book (id int,name varchar(20), price double)";
conn.Execute(sql);
sql = "insert into book values(@id1,@name1,@price1)";
conn.Execute(sql, new Book());
sql = "select * from book";
var books = conn.Query<Book>(sql);
Console.ReadLine();
}
}
public class Book
{
[Column("name")]
public string Name1 { get; set; }
[Column("id")]
public int Id1 { get; set; }
[Column("price")]
public double Price1 { get; set; }
}
public class CustomTypeMap<T> : SqlMapper.ITypeMap
{
public ConstructorInfo FindConstructor(string[] names, Type[] types)
{
return null;
}
public ConstructorInfo FindExplicitConstructor()
{
return typeof(Book).GetConstructor(new Type[0]);
}
public SqlMapper.IMemberMap GetConstructorParameter(ConstructorInfo constructor, string columnName)
{
return null;
}
public SqlMapper.IMemberMap GetMember(string columnName)
{
return new CustomMemberMap(columnName, _dict[columnName]);
}
private Dictionary<string, PropertyInfo> _dict = new Dictionary<string, PropertyInfo>();
public CustomTypeMap()
{
Type type = typeof(T);
var ps = type.GetProperties();
foreach (var p in ps)
{
var at = p.GetCustomAttribute<ColumnAttribute>();
if (at != null)
{
if (!string.IsNullOrWhiteSpace(at.ColumnName))
_dict.Add(at.ColumnName, p);
}
}
}
}
[AttributeUsage(AttributeTargets.Property)]
public class ColumnAttribute : Attribute
{
public string ColumnName { get; }
public ColumnAttribute(string columnName)
{
ColumnName = columnName;
}
}
public class CustomMemberMap : SqlMapper.IMemberMap
{
public CustomMemberMap(string column,PropertyInfo propertyInfo)
{
ColumnName = column;
Property = propertyInfo;
}
public string ColumnName { get; }
public Type MemberType => Field?.FieldType ?? Property?.PropertyType ?? Parameter?.ParameterType;
public PropertyInfo Property { get; }
public FieldInfo Field { get; }
public ParameterInfo Parameter { get; }
}
本文版權(quán)歸腿腿教學(xué)網(wǎng)及原創(chuàng)作者所有,未經(jīng)授權(quán),謝絕轉(zhuǎn)載。
上一篇:二次開(kāi)發(fā)教程:Hello entity framework
下一篇:二次開(kāi)發(fā)教程:orm 里使用Emit
推薦專題