使用Dapper.Net ORM,如何将存储过程输出转换为具体类型?

时间:2012-04-13 21:20:27

标签: c#-4.0 stored-procedures sql-server-2008-r2 metadata dapper

使用Entity Framework我可以从我正在处理的项目的数据库中的大多数sprocs创建具体的类。但是,某些sprocs使用动态SQL,因此没有为sproc返回元数据。

所以对于那个sproc,我手动创建了一个具体类,现在想要将sproc输出映射到这个类并返回这个类型的列表。

使用以下方法,我可以得到一组对象:

                var results = connection.Query<object>("get_buddies", 
                    new {   RecsPerPage = 100,
                            RecCount = 0,
                            PageNumber = 0,
                            OrderBy = "LastestLogin",
                            ProfileID = profileID,
                            ASC = 1}, 
                        commandType: CommandType.StoredProcedure);

我的具体课程包含

[DataContractAttribute(IsReference=true)]
[Serializable()]
public partial class LoggedInMember : ComplexObject
{

   /// <summary>
    /// No Metadata Documentation available.
    /// </summary>
    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.Int16 RowID
    {
        get
        {
            return _RowID;
        }
        set
        {
            OnRowIDChanging(value);
            ReportPropertyChanging("RowID");
            _RowID = StructuralObject.SetValidValue(value);
            ReportPropertyChanged("RowID");
            OnRowIDChanged();
        }
    }
    private global::System.Int16 _RowID;
    partial void OnRowIDChanging(global::System.Int16 value);
    partial void OnRowIDChanged();

    [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
    [DataMemberAttribute()]
    public global::System.String NickName
    {
        get
        {
            return _NickName;
        }
        set
        {
            OnNickNameChanging(value);
            ReportPropertyChanging("NickName");
            _NickName = StructuralObject.SetValidValue(value, false);
            ReportPropertyChanged("NickName");
            OnNickNameChanged();
        }
    }
    private global::System.String _NickName;
    partial void OnNickNameChanging(global::System.String value);
    partial void OnNickNameChanged();
    .
    .
    .

无需迭代结果并将输出参数添加到LoggedInMember对象,如何动态映射这些参数以便我可以通过WCF服务返回它们的列表?

如果我尝试var results = connection.Query<LoggedInMember>("sq_mobile_get_buddies_v35", ...,我会收到以下错误:

  

System.Data.DataException:解析列0时出错(RowID = 1 - Int64)   ---&GT; System.InvalidCastException:指定的强制转换无效。在反序列化......

2 个答案:

答案 0 :(得分:1)

猜测你的SQL列是bigint(即Int64 a.k.a。long),但你的.Net类型有一个n Int16属性。

你可以玩转换并忽略存储过程,例如:

var results = connection.Query<LoggedInMember>("select cast(9 as smallint) [RowID] ...");

您只需选择要返回对象的属性和类型。 (smallint是SQL等效于Int16

答案 1 :(得分:0)

解决方法是使用EF创建一个从sproc派生的复杂对象:

    public ProfileDetailsByID_Result GetAllProfileDetailsByID(int profileID)
    {
        using (IDbConnection connection = OpenConnection("PrimaryDBConnectionString"))
        {
            try
            {
                var profile = connection.Query<ProfileDetailsByID_Result>("sproc_profile_get_by_id",
                    new { profileid = profileID },
                    commandType: CommandType.StoredProcedure).FirstOrDefault();

                return profile;
            }
            catch (Exception ex)
            {
                ErrorLogging.Instance.Fatal(ex);        // use singleton for logging
                return null;
            }
        }
    }

在这种情况下,ProfileDetailsByID_Result是我通过复杂类型创建过程使用Entity Framework手动创建的对象(右键单击模型图,选择Add / Complex Type ...,或使用复杂类型树RHS)。

谨慎之词

因为此对象的属性是从sproc派生的,所以EF无法知道属性是否可以为空。对于任何可以为空的属性类型,您必须通过选择属性并将其Nullable属性设置为true来手动配置这些