Clarification of Dapper Example Code

三世轮回 提交于 2019-12-12 09:34:10

问题


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);

回答1:


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:

select 'foo', 1

...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.



来源:https://stackoverflow.com/questions/6379478/clarification-of-dapper-example-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!