0

In my project i am using MVC3 and Entity F/w . I have an excel sheet with tabular data i am able to retrieve the data from excel sheet to datatable or a list but now how i can store it to my Sqlserver table using Entity framework only .If anyone know the solution please help me .

my excel sheet

User_Id Account_Name Account_Date Current_Balance Age 1 Abcd 12/10/2013 5000 26 2 Wxyz 10/12/2010 2100 31 3 Klmn 1/1/2000 3500 23 4 Pqrs 10/1/2001 8900 30 5 Tuvw 12/10/1990 9000 27

Retrieve data store in List

        var excel = new ExcelQueryFactory("E:\\ExcelMvc.xlsx");
        var dataContent = from c in excel.Worksheet("Sheet1")
                          select c;

        List<ExcelMvcModels> LstData = new List<ExcelMvcModels>();

        foreach (var item in dataContent)
        {
            LstData.Add(new ExcelMvcModels()
            { User_Id=item[0],
             Account_Name = item[1],
             Account_Date=item[2],
             Current_Balance=item[3],
             Age=Convert.ToInt32(item[4])

            });
        }

OR retrieve data store in Datatable

        DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add(new System.Data.DataColumn("User_Id", typeof(string)));
        dt.Columns.Add(new System.Data.DataColumn("Account_Name", typeof(string)));
        dt.Columns.Add(new System.Data.DataColumn("Account_Date", typeof(string)));
        dt.Columns.Add(new System.Data.DataColumn("Current_Balance", typeof(string)));
        dt.Columns.Add(new System.Data.DataColumn("Age", typeof(int)));

        if (dataContent != null)
        {
            foreach (var item in dataContent)
            {
                dr = dt.NewRow();
                dr[0] = item[0].Value.ToString();
                dr[1] = item[1].Value.ToString();
                dr[2] = item[2].Value.ToString();
                dr[3] = item[3].Value.ToString();
                dr[4] = item[4].Value.ToString();

                dt.Rows.Add(dr);
            }
        }
4

1 回答 1

0

循环遍历您的列表并将 ExcelMvcModels 的每个实例添加到您的上下文中:

using (var context = new ModelsContext())
{
    foreach (var m in LstData)
    {
      context.Models.Add(m);
    }

    context.SaveChanges();
}

有关更多信息,请浏览/阅读 msdn 站点“ Entity Framweork 入门

于 2013-08-27T09:04:21.027 回答