Dapper Extensions dbConnection.Get<Object>
问题:Dapper扩展dbConnection.Get(personId)
我有一个名为Person:
的模型
1 2 3 4 5 | Person { public int PersonId { get; set; } public string Name { get; set; } } |
在数据库中,我有此表:
1 2 3 | data.Persons Pers_Id Pers_Name |
在没有任何自定义映射的情况下尝试执行此操作时,出现错误"无效的对象名称'Person'。"
我认为这是一个映射问题,因为当我完全映射带有前缀" Pers_"的模型并使用" data.Persons"时,
取得作品。
但是有没有一种方法可以自动使用前缀映射?我正在使用的数据库有许多不同的表
具有不同的首选项。
我也已经将所有内容映射到实体框架。是否有可能从中获取地图设置
实体DbModelBuilder?
Dapper-Extensions是基于约定的。对于模式,它使用.dbo;对于主键,它使用ID。如果您的表不符合约定,则必须创建一个自定义映射。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class MyModelMapper : ClassMapper<MyModel> { public MyModelMapper() { //use different table name Table("table_name"); //use a custom schema Schema("not_dbo_schema"); //have a custom primary key Map(x => x.ThePrimaryKey).Key(KeyType.Assigned); //Use a different name property from database column Map(x=> x.Foo).Column("Bar"); //Ignore this property entirely Map(x=> x.SecretDataMan).Ignore(); //optional, map all other columns AutoMap(); } } |
一种替代方法是使用Dapper并编写内联查询:
1 | connection.Query("select * from foo.table where myId = {myId}", new {myId}) |
更新:
另一种替代方法是使用代码生成和T4文本模板
这是一个简单的例子