如何开始使用Dapper.Mapper?

时间:2017-07-25 03:42:21

标签: c# dapper

我使用Dapper.Mapper直接将Sql查询映射到我的应用程序类。我相信Dapper.Mapper只是原始ORM Dapper上的一个语法糖涂层。但是,由于演示和示例非常少,我仍然无法从头开始。但是我按照他们的git页面尝试了这个:

var sql="Select * from Students where Grades>90"'
var conn=new MySqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
var studentRecord=conn.Query<Students, TopStudents>(sql);

我的POCO模型是:

//Db table    
public class Students
{
    public int Id{get;set;}
    public string Name{get;set;}
    public float Grades{get;set;}
}

public class TopStudents
{
    public int Id{get;set;}
    public string Name{get;set;}
    public string Grades{get;set;}
    //...Few more properties
}

但是我得到了以下异常,No Writable Property for TopStudents found in types Students

我错过了什么吗?请分享任何快速演示或教程。甚至没有适当的文档,我可以找到异常的原因并自行解决。如何开始使用Dapper.Mapper?

1 个答案:

答案 0 :(得分:1)

请参阅文档here,示例查询使用select *并使用内部联接,因此它返回了Employee和Department对象。如果它只返回Employee对象,那么代码将如下所示:

var sql = @"select * from Employee";

var employee = connection.Query<Employee, Department>(sql);

将此应用于您的代码:

var sql="Select * from Students where Grades>90"'
var conn=new MySqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
var studentRecord=conn.Query<Students>(sql);

如果您想要返回StudentsTopStudents,那么您可以将其更改为:

var sql="Select * from Students s
INNER JOIN TopStudents ts where s.Id = ts.Id AND s.Grades>90"'
var conn=new MySqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
var studentRecord=conn.Query<Students, TopStudents>(sql);
相关问题