public long AddItem <T>(T item) where T : BaseModel { try { item.CreateDate = DateTime.Now; db.Set <T>().Add(item); db.SaveChangesAsync(); return(item.Id); } catch { return(0); } }
public bool ExportToFile <T1, T2>(string savePath = "D:\\TEMP\\") where T1 : class { var allItems = db.Set <T1>().ToList(); string fileName = DateTime.Now.ToString("yyMMddHHmmss") + "." + typeof(T1).Name + ".csv"; //var allItems = db.Part.ToList(); bool header = true; //AutoMapper.Mapper.Initialize(cfg => { cfg.CreateMap<T1, T2>(); }); using (StreamWriter writer = System.IO.File.CreateText(Path.Combine(savePath, fileName))) { foreach (T1 item in (List <T1>)allItems) { var expPart = AutoMapper.Mapper.Map <T1, T2>(item); if (header) { var title_list = new List <object>(); foreach (PropertyInfo property in expPart.GetType().GetProperties()) { title_list.Add(property.Name); } var headerLine = string.Join(Constants.FILE_DELIMITER.ToString(), title_list); writer.WriteLine(headerLine); header = false; } var field_list = new List <object>(); foreach (PropertyInfo property in expPart.GetType().GetProperties()) { var val = property.GetValue(expPart, null); field_list.Add(val); } var line = string.Join(Constants.FILE_DELIMITER.ToString(), field_list); writer.WriteLine(line); } return(true); } }