如何使用Entity Framework database.sqlquery填充数据集?

时间:2015-04-10 14:53:32

标签: c# sql entity-framework

我使用EntityFramewrok,我想用存储过程绑定一个类。

我的程序选择查询:

Select RecordId,Name_TrTr Name from Institute where Name_TrTr  like ('%'+@Search+'%')
 Order by Name
 OFFSET @Start ROWS
 FETCH NEXT @Length ROWS ONLY

Select @TotalCount as TotalCount, @FilteredCount FilteredCount

我的课程:

public class InstituteTestModel
{
    public int RecordId { get; set; }
    public string Name { get; set; }
}

public class ProcedureDetail
{
    public int TotalCount { get; set; }
    public int FilteredCount { get; set; }
}

public class ProcedureClass
{
    public InstituteTestModel Model { get; set; }
    public ProcedureDetail Detail { get; set; }
}

C#执行:

var q = Connection.Database<ProcedureClass>(query);

1 个答案:

答案 0 :(得分:1)

您可以将结果放在数据表中并将数据表转换为列表

public static class Helper
{
    /// <summary>
    /// Converts a DataTable to a list with generic objects
    /// </summary>
    /// <typeparam name="T">Generic object</typeparam>
    /// <param name="table">DataTable</param>
    /// <returns>List with generic objects</returns>
    public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()
    {
        try
        {
            List<T> list = new List<T>();

            foreach (var row in table.AsEnumerable())
            {
                T obj = new T();

                foreach (var prop in obj.GetType().GetProperties())
                {
                    try
                    {
                        PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);
                        propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);
                    }
                    catch
                    {
                        continue;
                    }
                }

                list.Add(obj);
            }

            return list;
        }
        catch
        {
            return null;
        }
    }
}