【问题标题】:How to return more than one element list?如何返回多个元素列表?
【发布时间】:2019-10-31 21:38:31
【问题描述】:

我有一个存储过程,它将返回我数据库中的所有记录,我想使用 linq 过滤该结果,但问题是它只会返回一条记录,尽管我有两条记录要返回。

客户控制器

public class CustomerController : ApiController
    {
        List<CustomerModel> customers = new List<CustomerModel>();
        private CustomerController()
        {

            var _data = ViewCustomer();
            if (_data.Rows.Count > 0)
            {
                customers = (from DataRow _dr in _data.Rows
                             select new CustomerModel()
                             {
                                 custId = Convert.ToInt32(_dr["custId"]),
                                 custName = Convert.ToString(_dr["custName"]),
                                 custAddress = Convert.ToString(_dr["custAddress"]),
                                 custContact = Convert.ToString(_dr["custContact"]),
                                 custStatus = Convert.ToString(_dr["custStatus"]),
                                 agentId = Convert.ToInt32(_dr["agentId"]),
                                 agentContact = Convert.ToString(_dr["agentContact"])
                             }).ToList();
            }
        }

        // GET: api/Customer
        public List<CustomerModel> Get()
        {
            return customers;
        }

        // GET: api/Customer/5
        public CustomerModel Get(string num)
        {
            return customers.Where(x => x.agentContact.Equals(num)).FirstOrDefault();
        }

数据存储库

 namespace DataLibrary.Repository
    {
        public class DataRepository
        {

            public static DataTable ViewCustomer()
            {
                try
                {
                    DataLayers CustData = new DataLayers();
                    CustData.cmdType = CommandType.StoredProcedure;
                    CustData.SQL = "CustomerStoredProcedure";
                    CustData.paramVal = new string[,]
                    {
                        { "@custId", ""},
                        { "@custName", ""},
                        { "@custAddress", ""},
                        { "@custContact", ""},
                        { "@custStatus", ""},
                        { "@agentId", ""},
                        { "@statement", "Select"}
                    };
                    return CustData.GetData();
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }

这是存储过程。

create procedure CustomerStoredProcedure
     (
    custId int(11),
    custName varchar(100),
    custAddress varchar(100),
    custContact varchar(20),
    custStatus varchar(20),
    agentId int(11),
    statement varchar(30)
    )
    begin
    if statement = 'Select' then
    select c.custId, c.custName, c.custAddress, c.custContact, c.custStatus, c.agentId,
    a.agentId, a.agentContact 
    from customer c 
    inner join agent a on c.agentId = a.agentId;
    elseif statement = 'Insert' then
    insert into customer ( custName, custAddress, custContact, custStatus, agentId) 
    values (custName, custAddress, custContact, custStatus, agentId);
    elseif statement = 'Update' then
    update customer set custName = custName, custAddress = custAddress,
    custContact = custContact, custStatus = custStatus, agentId = agentId where
    custtId = custId;
    elseif statement = 'Delete' then
    delete from customer where custId = custId;
    end if;

这是我的数据层

public class DataLayers
    {
        public static string success = "Record successfully added!";
        public static string failed = "Error: Data could not added, Please check your inputted data(s)!";

        public CommandType cmdType { get; set; }
        public string SQL { get; set; }
        public string[,] paramVal { get; set; }

        public static MySqlConnection Config()
        {
            var conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString.ToString());
            conn.Open();
            return conn;
        }

        public DataTable GetData()
        {
            MySqlCommand cmd = new MySqlCommand(this.SQL, Config());
            cmd.CommandType = cmdType;
            cmd.CommandTimeout = 0;
            if (this.paramVal != null)
            {
                for (int i = 0; i <= paramVal.GetUpperBound(0); i++)
                {
                    cmd.Parameters.AddWithValue(this.paramVal[i, 0].ToString().Trim(), this.paramVal[i, 1].ToString().Trim());
                }
            }
            DataTable dt = new DataTable();
            var dataAdapter = new MySqlDataAdapter(cmd);
            dataAdapter.Fill(dt);
            dataAdapter.Dispose();
            cmd.Dispose();
            Config().Close();
            return dt;
        }

        public DataTable GetData(bool Error)
        {
            try
            {
                MySqlCommand cmd = new MySqlCommand(this.SQL, Config());
                cmd.CommandType = cmdType;
                cmd.CommandTimeout = 0;
                if (this.paramVal != null)
                {
                    for (int i = 0; i <= paramVal.GetUpperBound(0); i++)
                    {
                        cmd.Parameters.AddWithValue(this.paramVal[i, 0].ToString().Trim(), this.paramVal[i, 1].ToString().Trim());
                    }
                }
                DataTable dt = new DataTable();
                var dataAdapter = new MySqlDataAdapter(cmd);
                dataAdapter.Fill(dt);
                dataAdapter.Dispose();
                cmd.Dispose();
                Config().Close();
                return dt;
            }
            catch (Exception ex)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Error");
                dt.Columns.Add("Message");
                dt.Rows.Add("Error: ", ex.Message.Replace("Tables", "Table").Replace("MySql", "Database"));
                return dt;
            }
        }
    }

这是我的数据仓库

 public class DataRepository
    {
        public static DataTable ViewAgent()
        {
            try
            {

                DataLayers AgentData = new DataLayers();
                AgentData.cmdType = CommandType.StoredProcedure;
                AgentData.SQL = "AgentStoredProcedure";
                AgentData.paramVal = new string[,]
                {
                    { "@agentId", "" },
                    { "@agentName", ""},
                    { "@agentAddress", ""},
                    { "@agentContact", ""},
                    { "@agentStatus", ""},
                    { "@catId", ""},
                    { "@statement", "Select"}
                };
                return AgentData.GetData();
            }
            catch (Exception)
            {
                throw;
            }
        }

        public static DataTable ViewCustomer()
        {
            try
            {
                DataLayers CustData = new DataLayers();
                CustData.cmdType = CommandType.StoredProcedure;
                CustData.SQL = "CustomerStoredProcedure";
                CustData.paramVal = new string[,]
                {
                    { "@custId", ""},
                    { "@custName", ""},
                    { "@custAddress", ""},
                    { "@custContact", ""},
                    { "@custStatus", ""},
                    { "@agentId", ""},
                    { "@statement", "Select"}
                };
                return CustData.GetData();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

返回所有记录

只返回一条记录,(错误的结果)

这是正确的记录结果

【问题讨论】:

  • 在不知道procedure/data layer 的底层实现的情况下,很难说结果有什么问题。但我的猜测可能是您的 select 语句中存在一个限制为单个记录的 Where 条件,或者您的 DataLayers 类实现中存在 1 记录的 default 限制。

标签: c# asp.net-mvc linq asp.net-web-api


【解决方案1】:

很多问题。

  • 为什么要有私有构造函数?
  • DataLayers 是什么,这是一些国产数据访问库吗?
  • 为什么存储过程不允许搜索@agentContact
  • 为什么在控制器构建时从数据库中加载所有数据,而不是按需过滤?

等等。但是假设您坚持使用这种方法,那么您已经为您的需求定义了错误的签名和逻辑。您想返回一个列表而不是单个项目:

public List<CustomerModel> Get(string num)
{
    return customers.Where(x => x.agentContact.Equals(num)).ToList();
}

【讨论】:

  • 现在我发布我所有的代码先生..对不起,我是 C# MVC 的新手,这就是为什么对如何制作干净的代码没有足够的想法..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 2021-07-07
  • 2023-03-07
  • 2021-06-24
  • 1970-01-01
  • 2021-02-07
相关资源
最近更新 更多