【问题标题】:Populate database with IEnumerable objects from CSV file [closed]使用 CSV 文件中的 IEnumerable 对象填充数据库 [关闭]
【发布时间】:2017-02-14 15:21:10
【问题描述】:

我有一个 CSV 文件,其中包含所有产品,我在新类中有一个方法将它们转换为 C# 产品对象,这些对象存储在 IEnumerable 类型的变量中:

public class ReadCSVFile
{
    public List<Product> ProductsList;

    public ReadCSVFile()
    {

        var path = @"/Content/TrendyDinersLimited_Self_ProductUpdateTemplate.csv";

        var CSVProducts = from line in File.ReadAllLines(path).Skip(1)
                          let columns = line.Split(',')
                          select new Product
                          {
                              Id = int.Parse(columns[0]),
                              Name = columns[1],
                              Price = int.Parse(columns[4])
                          };
    }
}

我的问题是,既然我有一个来自 CSV 文件的产品列表,我应该如何将它们填充到我的数据库中(作为一次性导入)?通常,管理员会先创建一个类别,然后单击一个类别来添加产品。

我在 Visual Studio 中使用 ASP.NET MVC 模板,我有三个主要控制器:HomeController(显示类别和产品)、CategoryController(管理员授权)、ProductController(管理员授权)。我还使用 Microsoft SQL Server 的直接连接字符串。

【问题讨论】:

  • 你是在使用 ORM,还是直接连接到数据库?
  • 后者——直接连接数据库。

标签: c# sql-server asp.net-mvc csv


【解决方案1】:

你有两个选择。如果您将代码编写为一次性导入实用程序,则可以直接连接到 SQL Server 以插入数据。

        string sqlInsertStmt = "INSERT INTO PRODUCT (id,name,price) VALUES (@id, @name, @price)";
        string connectionString = "sqlserver connection string";

        //sample connection string can be like
        //connectionString="Data Source=ServerName;Initial Catalog=DatabaseName;Integrated Security=False;User Id=userid;Password=password;MultipleActiveResultSets=True";

        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            foreach (var product in CSVProducts)
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = sqlInsertStmt;
                    cmd.Parameters.AddWithValue("@id", product.Id);
                    cmd.Parameters.AddWithValue("@name", product.Name);
                    cmd.Parameters.AddWithValue("@val", product.Price);
                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch(SqlException e)
                    {
                        //log exception and handle error
                    }
                }
            }
        }

SQL server connection strings 的示例

但是,如果您想要更易于维护的东西,您可以使用 EF6 作为您的 ORM 层。 请阅读这篇解释如何get started with EF6 and existing database

【讨论】:

  • 我正在尝试这个,但你的意思是 cmd.CommandText 而不是 cmd.CommandString?
  • 是的,它是命令文本...抱歉错字。我已经更新了我的答案
  • 您可以在将数据读入 CSVProducts 变量后在 ReadCSVFile 中调用它。您不妨调用 ProductsLoader 类。在构造函数方法中执行一些繁重的操作是不好的做法。您可能应该创建两种方法。 GetProducts 返回产品列表,然后是另一个名为 SaveProducts 的方法,该方法将产品列表作为输入并执行保存到数据库。然后从您的业务层或 MVC 控制器调用这两个方法。
【解决方案2】:

就我个人而言,我会使用 Dapper.Net 来做这样简单的事情。

如果使用 Dapper.Contrib (https://www.nuget.org/packages/Dapper.Contrib/) 你可以用表格和关键属性来装饰你的班级,让自己的生活更轻松

[Table ("Products")]
public class Product
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public int Price { get; set; }
}

然后你可以这样插入

var connString = System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
    using (var connection = new SqlConnection(connString)) {
        foreach(var product in CSVProducts){        
            connection.Insert(product);
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多