目的将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>());//定义映射规则
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; }
}