繁体   English   中英

在MVC中的模型中存储从sql查询返回的列表

[英]Storing a list returned from a sql query in a model within MVC

我下面的代码返回大约2000项数据的列表。 我想将其返回到model并将其传递回view

var clientData = db.Clients.Where(x => x.Firm == firm).ToList();
List<ClientEmployees> clientEmployees = new List<ClientEmployees>();

foreach(var client in clientData)
{
      //store in the in the clientEmployees list              
}

但是我真的不想遍历1000行数据来将它们存储到列表中。 以后我需要处理这些数据,这就是为什么我认为最好使用以后可以处理的model 有什么更好的想法吗?

请尝试以下代码。 该列表包含原始数据表的链接,因此您无需复制数据并使用更多的内存。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication45
{
    class Program
    {
        static void Main(string[] args)
        {
            string connStr = "Enter Your connection strin gHere";
            string SQL = "Enter your SQL Here";

            SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);

            DataTable dt = new DataTable();
            adapter.Fill(dt);
            string firm  = "abc";

            List<DataRow> clientData = dt.AsEnumerable().Where(x => x.Field<string>("firm") == firm).ToList();


        }
    }

}

如果没有一堆字段,您可以选择列表

var clientEmployees = db.Clients.Where(x => x.Firm == firm)
                        .Select(a => new ClientEmployees {
                            Id = a.Id,
                            Name = a.Name,
                            etc..
                        })
                        .ToList();

如果有很多字段,可能值得研究AutoMapper或类似的东西。

.Select也可以使用Func <>,因此您可以在视图模型中执行类似的操作

public class ClientEmployees
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static Func<Client, ClientEmployees> FromEntity = item => new ClientEmployees()
    {
        Id = item.Id,
        Name = item.Name,
        //map all fields
    };
}

然后,当您从数据库上下文中选择时,只需使用。

var clientEmployees = db.Clients.Where(x => x.Firm == firm)
                    .Select(ClientEmployees.FromEntity)
                    .ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM