Dapper 示例代码的说明
我正在尝试理解 Dapper,似乎缺少一些非常基本的东西,有人可以解释一下从 Google 代码上的 Dapper 主页获取的以下代码,并解释为什么没有 From 子句,以及 Query 方法的第二个参数(动态)传递了一个匿名类型,我认为这是以某种方式设置命令对象,但希望用普通术语进行解释。
谢谢你, 斯蒂芬
public class Dog {
public int? Age { get; set; }
public Guid Id { get; set; }
public string Name { get; set; }
public float? Weight { get; set; }
public int IgnoredProperty {
get { return 1; }
}
}
var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
dog.Count().IsEqualTo(1);
dog.First().Age.IsNull();
dog.First().Id.IsEqualTo(guid);
I'm trying to grok Dapper and seem to be missing something very fundamental, can someone explain the following code taken from the Dapper home page on Google code and explain why there is no From clause, and the second param to the Query method (dynamic) is passed an anonymous type, I gather this is somehow setting up a command object, but would like an explanation in mere mortal terminology.
Thank you,
Stephen
public class Dog {
public int? Age { get; set; }
public Guid Id { get; set; }
public string Name { get; set; }
public float? Weight { get; set; }
public int IgnoredProperty {
get { return 1; }
}
}
var guid = Guid.NewGuid();
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
dog.Count().IsEqualTo(1);
dog.First().Age.IsNull();
dog.First().Id.IsEqualTo(guid);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
前两个示例只是不进行任何“真正的”数据访问,可能是为了保持简单。
是的,使用了一个连接(
connection.Query(...)
),但这只是因为这是调用 Dapper 方法的唯一方法(因为它们扩展了 IDbConnection 接口)。像这样的东西是完全有效的 SQL 代码:
...它只是动态“生成”其结果,而不实际从表中选择任何内容。
带有参数和匿名类型的示例:
vardog = connection.Query("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid } );
)...只是显示了 Dapper 提交 SQL 参数的能力匿名类型的形式。
同样,查询实际上并没有从表中选择任何内容,可能是为了保持简单。
The first two examples just don't do any "real" data access, probably in order to keep them simple.
Yes, there is a connection used (
connection.Query(...)
), but only because that's the only way to call Dapper's methods (because they extend the IDbConnection interface).Something like this is perfectly valid SQL code:
...it just does "generate" its result on the fly, without actually selecting anything from a table.
The example with the parameters and the anonymous type:
var dog = connection.Query<Dog>("select Age = @Age, Id = @Id", new { Age = (int?)null, Id = guid });
)...just shows Dapper's ability to submit SQL parameters in the form of an anonymous type.
Again, the query does not actually select anything from a table, probably in order to keep it simple.