C# 如何将sql读取器映射到对象中的列表

C# 如何将sql读取器映射到对象中的列表,c#,C#,我的数据库中有以下数据: 我有以下DTO来填写这些信息: public class LanguageDto : ILanguageDto { public int LanguageId { get; set; } public string LanguageName { get; set; } public string LangValue { get; set; } public IEnumerable<CountryFlag> LanguageF

我的数据库中有以下数据:

我有以下DTO来填写这些信息:

public class LanguageDto : ILanguageDto
{
    public int LanguageId { get; set; }
    public string LanguageName { get; set; }
    public string LangValue { get; set; }
    public IEnumerable<CountryFlag> LanguageFlagUrls { get; set; }
    public bool IsDefaultLanguage { get; set; }
}
放置只有一个languageId、LanguageName和LangValue实例的FlagURL关联列表的最佳方法是什么

到目前为止,如果我这样做,列表中有6个实例:

var urls = new List<CountryFlag>();
var unparsedLanguages = new List<LanguageDto>();

while (rdr.Read())
{
    var langDtop = new LanguageDto();
    langDtop.LanguageId = rdr.GetInt32(0);
    langDtop.LanguageName = rdr[1].ToString();
    langDtop.LangValue = rdr[2].ToString();
    langDtop.LanguageFlagUrls = new List<CountryFlag>{new CountryFlag { FlagUrl = rdr[3].ToString()}};
    unparsedLanguages.Add(langDtop);
}

有没有建议没有嵌套的foreach,或者只有一个漂亮的linq表达式?一切都会有帮助的,非常感谢

您可以使用db直接调用来列出,这是更好的方法

//Where TransactionDto is your List 

//And TRANSACTION_ID and FMS_STATUS are Parameters passing

CallStoredProcedureForMultipleTable<TransactionDto, dynamic>(
                                                        "proc_UpdateFmsStatusByTransactionId",
new Dictionary<dynamic, Tuple<dynamic, bool, string>>(){
{ "TRANSACTION_ID" ,Tuple.Create<dynamic,bool,string(l_TransactionDto.Tm_TRANSACTION_ID,false,null)},
{ "FMS_STATUS" ,Tuple.Create<dynamic,bool,string>(FmsStatus.Processed,false,null)}
},
out l_SpResponseCode,
out l_SpResponseDescription);
//其中TransactionDto是您的列表
//事务ID和FMS状态是传递的参数
CallStoredProcedureForMultipleTable(
“proc_UpdateFmsStatusByTransactionId”,
新字典(){

{“TRANSACTION_ID”,Tuple.Create您可以使用另一个更容易理解的答案

  if (reader.HasRows)
                        {
                            Type1 = DataReaderMapToList<T1>(reader).ToList();
                            while (reader.NextResult())
                                Type2 = DataReaderMapToList<T2>(reader).ToList();
                        }


//here is the other functions

public static bool HasColumn(this IDataRecord p_IDataRecord, string p_ColumnName)
    {
        string l_FuncName = "HasColumn";

        try
        {
            for (int i = 0; i < p_IDataRecord.FieldCount; i++)
            {
                if (p_IDataRecord.GetName(i).Equals(p_ColumnName, StringComparison.InvariantCultureIgnoreCase))
                    return true;
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(l_ClassName, l_FuncName, "Error Message", ex.Message);
        }
        return false;
    }
    public static List<T> DataReaderMapToList<T>(IDataReader p_DataReader)
    {
        List<T> list = new List<T>();
        T obj;
        try
        {
            while (p_DataReader.Read())
            {
                obj = Activator.CreateInstance<T>();
                foreach (System.Reflection.PropertyInfo prop in obj.GetType().GetProperties())
                {
                    if (p_DataReader.HasColumn(prop.Name) && !object.Equals(p_DataReader[prop.Name], DBNull.Value))
                        prop.SetValue(obj, p_DataReader[prop.Name], null);
                }
                list.Add(obj);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("OtherServicesBll", "DataReaderMapToList ", "Error Stacktrace", ex.StackTrace, "Error Message", ex.Message);
        }
        return list;
    }

if(reader.HasRows)
{
Type1=DataReaderMattoList(reader.ToList();
while(reader.NextResult())
Type2=DataReaderMattoList(reader.ToList();
}
//下面是其他函数
公共静态bool HasColumn(此IDataRecord p_IDataRecord,字符串p_ColumnName)
{
字符串l_FuncName=“HasColumn”;
尝试
{
for(int i=0;i
所以我修改了你给我的代码,但是.NextResult从来没有实现过。遗憾的是,它无法将URL列表映射到每个对象中:if(rdr.HasRows){availableLanguages=DataReaderMattoList(rdr.ToList();while(rdr.NextResult())URL=DataReaderMapToList(rdr).ToList();}
//Where TransactionDto is your List 

//And TRANSACTION_ID and FMS_STATUS are Parameters passing

CallStoredProcedureForMultipleTable<TransactionDto, dynamic>(
                                                        "proc_UpdateFmsStatusByTransactionId",
new Dictionary<dynamic, Tuple<dynamic, bool, string>>(){
{ "TRANSACTION_ID" ,Tuple.Create<dynamic,bool,string(l_TransactionDto.Tm_TRANSACTION_ID,false,null)},
{ "FMS_STATUS" ,Tuple.Create<dynamic,bool,string>(FmsStatus.Processed,false,null)}
},
out l_SpResponseCode,
out l_SpResponseDescription);
 public static List<dynamic> CallStoredProcedureForMultipleTable<T1, T2>(string p_SpName, IDictionary<dynamic, Tuple<dynamic, bool, string>> p_Param, out string p_OutResposneCode, out string p_OutResposneDescription)
    {

        p_OutResposneCode = ResponseCode.Success;
        p_OutResposneDescription = TransactionStatus.Success;
        List<dynamic> retVal = new List<dynamic>();
        List<T1> Type1 = null; List<T2> Type2 = null;
        using (SqlConnection connection = new SqlConnection(CommonObjects.GetConnectionString()))
        {
            try
            {
                using (SqlCommand cmd = new SqlCommand(p_SpName, connection))
                {

                    if (connection != null && connection.State != ConnectionState.Open)
                    {
                        connection.Close();
                        connection.Open();
                    }
                    cmd.CommandType = CommandType.StoredProcedure;

                    foreach (var data in p_Param)
                    {
                        var sqlParam = new SqlParameter("@" + data.Key, data.Value.Item1);
                        if (data.Value.Item2)
                        {
                            sqlParam.SqlDbType = SqlDbType.Structured;
                            sqlParam.TypeName = "dbo." + data.Value.Item3;
                        }
                        cmd.Parameters.Add(sqlParam);
                    }

                    SqlParameter l_OutResponseCode = new SqlParameter("@ResponseCode", SqlDbType.VarChar, 10) { Direction = ParameterDirection.Output };
                    cmd.Parameters.Add(l_OutResponseCode);
                    SqlParameter l_OutResponseDescription = new SqlParameter("@ResponseDescription", SqlDbType.VarChar, 200) { Direction = ParameterDirection.Output };
                    cmd.Parameters.Add(l_OutResponseDescription);


                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            Type1 = DataReaderMapToList<T1>(reader).ToList();
                            while (reader.NextResult())
                                Type2 = DataReaderMapToList<T2>(reader).ToList();
                        }
                    }
                    p_OutResposneCode = l_OutResponseCode.Value.ToString();
                    p_OutResposneDescription = l_OutResponseDescription.Value.ToString();

                    if (connection != null && connection.State == ConnectionState.Open)
                    {
                        connection.Close();
                        connection.Dispose();
                    }

                }
            }
            catch (Exception ex)
            {
                if (connection != null && connection.State == ConnectionState.Open)
                {
                    connection.Close();
                    connection.Dispose();
                }

                p_OutResposneCode = ResponseCode.Error;
                p_OutResposneDescription = ex.Message;
                Logger.LogError("OtherServicesBLL", "CallStoredProcedureForMultipleTable ", "Error Stacktrace", ex.StackTrace, "Error Message", ex.Message,"spname", p_SpName);
            }
        }
        retVal.Add(Type1);
        retVal.Add(Type2);
        return retVal;
    }
    public static bool HasColumn(this IDataRecord p_IDataRecord, string p_ColumnName)
    {
        string l_FuncName = "HasColumn";

        try
        {
            for (int i = 0; i < p_IDataRecord.FieldCount; i++)
            {
                if (p_IDataRecord.GetName(i).Equals(p_ColumnName, StringComparison.InvariantCultureIgnoreCase))
                    return true;
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(l_ClassName, l_FuncName, "Error Message", ex.Message);
        }
        return false;
    }
    public static List<T> DataReaderMapToList<T>(IDataReader p_DataReader)
    {
        List<T> list = new List<T>();
        T obj;
        try
        {
            while (p_DataReader.Read())
            {
                obj = Activator.CreateInstance<T>();
                foreach (System.Reflection.PropertyInfo prop in obj.GetType().GetProperties())
                {
                    if (p_DataReader.HasColumn(prop.Name) && !object.Equals(p_DataReader[prop.Name], DBNull.Value))
                        prop.SetValue(obj, p_DataReader[prop.Name], null);
                }
                list.Add(obj);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("OtherServicesBll", "DataReaderMapToList ", "Error Stacktrace", ex.StackTrace, "Error Message", ex.Message);
        }
        return list;
    }
  if (reader.HasRows)
                        {
                            Type1 = DataReaderMapToList<T1>(reader).ToList();
                            while (reader.NextResult())
                                Type2 = DataReaderMapToList<T2>(reader).ToList();
                        }


//here is the other functions

public static bool HasColumn(this IDataRecord p_IDataRecord, string p_ColumnName)
    {
        string l_FuncName = "HasColumn";

        try
        {
            for (int i = 0; i < p_IDataRecord.FieldCount; i++)
            {
                if (p_IDataRecord.GetName(i).Equals(p_ColumnName, StringComparison.InvariantCultureIgnoreCase))
                    return true;
            }
        }
        catch (Exception ex)
        {
            Logger.LogError(l_ClassName, l_FuncName, "Error Message", ex.Message);
        }
        return false;
    }
    public static List<T> DataReaderMapToList<T>(IDataReader p_DataReader)
    {
        List<T> list = new List<T>();
        T obj;
        try
        {
            while (p_DataReader.Read())
            {
                obj = Activator.CreateInstance<T>();
                foreach (System.Reflection.PropertyInfo prop in obj.GetType().GetProperties())
                {
                    if (p_DataReader.HasColumn(prop.Name) && !object.Equals(p_DataReader[prop.Name], DBNull.Value))
                        prop.SetValue(obj, p_DataReader[prop.Name], null);
                }
                list.Add(obj);
            }
        }
        catch (Exception ex)
        {
            Logger.LogError("OtherServicesBll", "DataReaderMapToList ", "Error Stacktrace", ex.StackTrace, "Error Message", ex.Message);
        }
        return list;
    }