Which ORM is the best when using Stored Procedures

前端 未结 8 1702
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 12:33

I have Business objects (DEVELOPERS WRITE) and some SPROCS (DBA WRITE)

Can anyone recommend a good object mapper to deal with this kind of setup.

I tried co

8条回答
  •  没有蜡笔的小新
    2020-12-05 13:07

    Disclaimer: I am the author of Dapper.


    If you are looking for a simple object mapper that handles mapping procs to business objects Dapper is a good fit.

    Keep in mind it ships with no "graph management", "identity map" and so on. It offers a bare bone, complete solution which covers many scenarios other ORMs do not.

    Nonetheless, it offers one of the fastest object materializers out there, which can be 10x faster than EF or even 100x faster than subsonic in some benchmarks.


    The trivial:

    create proc spGetOrder
       @Id int
    as 
    select * from Orders where Id = @Id
    select * from OrderItems where OrderId = @Id 
    

    Can be mapped with the following:

    var grid = cnn.QueryMultiple("spGetOrder", new {Id = 1}, commandType: CommandType.StoredProcedure);
    var order = grid.Read();
    order.Items = grid.Read(); 
    

    Additionally you have support for:

    1. A multi-mapper that allows you single rows to multiple objects
    2. Input/Output/Return param support
    3. An extensible interface for db specific parameter handling (like TVPs)

    So for example:

    create proc spGetOrderFancy
       @Id int,
       @Message nvarchar(100) output 
    as 
    set @Message = N'My message' 
    select * from Orders join Users u on OwnerId = u.Id where Id = @Id
    select * from OrderItems where OrderId = @Id
    return @@rowcount
    

    Can be mapped with:

    var p = new DynamicParameters(); 
    p.Add("Id", 1);
    p.Add("Message",direction: ParameterDirection.Output);
    p.Add("rval",direction: ParameterDirection.ReturnValue);
    var grid = cnn.QueryMultiple("spGetOrder", p, commandType: CommandType.StoredProcedure);
    var order = grid.Read((o,u) => {o.Owner = u; return o;});
    order.Items = grid.Read(); 
    
    var returnVal = p.Get("rval"); 
    var message = p.Get("message"); 
    

    Finally, dapper also allow for a custom parameter implementation:

    public interface IDynamicParameters
    {
       void AddParameters(IDbCommand command);
    }
    

    When implementing this interface you can tell dapper what parameters you wish to add to your command. This allow you to support Table-Valued-Params and other DB specific features.

提交回复
热议问题