How to insert model from mapping table

喜欢而已 提交于 2019-12-25 03:10:17

问题


I have idea to insert my model from excel using mapping from table. Because my excel hv more then 100 column. It will be tired if I code manualy like I do. I hv idea to save to database the name of header excel, the function, and row for my table

First, I read my excel then capture to dataset, then foreach dataset, then for each list mapping, then using if to know is empty or not, then read function using replace, then set model using mapping table

What I do:

[HttpPost]
public ActionResult upload(HttpPostedFileBase uploadFile)
{
    private DB_Entities db = new DB_Entities();
    dataset ds = new dataset();
    ds = GetFileExcel(uploadFile);

    foreach (DataRow dr in ds.Tables["Header$"].Rows)
    {   
        tbl_header header = new tbl_header();

        string name = dr["Name"].ToString();
        if (name != "") {
            var resultName = Convert.ToInt32(name);
            header.name = resultName;
        }

        string address = dr["Address"].ToString();
        if (address != "") {
            var resultAddress = DateTime.ParseExact(address, "dd MMM yyyy", provider);
            header.address = resultAddress;
        }

        string country = dr["Country"].ToString();
        if (country != "") {
            var resultCountry = db.tbl_Item.Where(a => a.Code == country).Select(a => a.Id).SingleOrDefault();
            header.country = ResultCountry;
        }

        db.tbl_header.Add(header);
        db.SaveChanges();
    }
}

public partial class tblT_Pengeluaran_Header
{
    public int name { get; set; }
    public DateTime address { get; set; }
    public int country { get; set; }
}

What I want:

[HttpPost]
public ActionResult upload(HttpPostedFileBase uploadFile)
{
    private DB_Entities db = new DB_Entities();
    dataset ds = new dataset();
    ds = GetFileExcel(uploadFile);
    var mapping = db.Tbl_Mapping.toList();

    foreach (DataRow dr in ds.Tables["Header$"].Rows)
    {
        tbl_header header = new tbl_header();

        //foreach list mapping to doing:
        //{
        //    string excel = ReadExcel
        //    if (excel != "") {
        //        string resultFunction = ReadFunction.Replace('[data]',excel);
        //        var result = Execute(resultFunction);
        //        header.ReadTable = result;
        //    }
        //} 

        db.tbl_header.Add(header);
        db.SaveChanges();
    }
}

table Mapping Example: Tbl_Mapping

table   | excel     | function
_____________________________________
name    | Name      | Convert.ToInt32([data]);
address | Address   | DateTime.ParseExact([data], "dd MMM yyyy", provider);
country | Country   | db.tbl_Item.Where(a => a.Code == [data]).Select(a => a.Id).SingleOrDefault();
.....
.....

How to do this? any idea??? Thank you


回答1:


I can see two issues in your code.

  1. The country object fetch from the database within the foreach
  2. The DB save within the foreach.

The above both are bad for the performance. Consider the below instead.

First, fetch all countries from the dataset and do single DB lookup and use AddRange instead of add.

For the Dataset to mapping object conversion, use Linq as below.

[HttpPost]
public ActionResult upload(HttpPostedFileBase uploadFile)
{
    private DB_Entities db = new DB_Entities();

    DataSet ds = GetFileExcel(uploadFile);

    string[] countryCodes = ds.Tables["Header$"].AsEnumerable().Select(row => row.Field<string>("country")).ToArray();

    var selectedCountries = db.tbl_Item.Where(q => countryCodes.Contains(q)).Select(s => new { Id = s.Id, Code = s.Code }).ToList();

    List<tbl_header>  headers = ds.Tables["Header$"].AsEnumerable().Select
    (
        row => new tbl_header
        {
            name = row.Field<string>("Name") == string.Empty ? 0 : int.Parse(row.Field<string>("Name")),
            address = row.Field<string>("Address") == string.Empty ? DateTime.MinValue : DateTime.ParseExact((row.Field<string>("Address")), "dd MMM yyyy", provider),
            country = selectedCountries.SingleOrDefault(q=> q.Code == row.Field<string>("Country")).Id
        }
    ).ToList();

    db.tbl_header.AddRange(headers);
    db.SaveChanges();
}


来源:https://stackoverflow.com/questions/52893131/how-to-insert-model-from-mapping-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!