i have two lists srsEmps
and destEmps
from classes
List<srsEmployee> srsEmps = db.srsEmployees.ToList();
List<destEmployee> destEmps = db2.destEmployees.ToList();
public class srsEmployee
{
public int Id { get; set; }
public string Name { get; set; }
public string EmpCode { get; set; }
public Nullable<decimal> Salary { get; set; }
public Nullable<system.datetime> StartDate { get; set; }
public Nullable<system.datetime> BOD { get; set; }
public int DepartmentId { get; set; }
public bool Active { get; set; }
public virtual srsDepartment srsDepartment { get; set; }
}
public class destEmployee
{
public int Id { get; set; }
public string Name { get; set; }
public string EmpCode { get; set; }
public Nullable<decimal> Salary { get; set; }
public Nullable<system.datetime> StartDate { get; set; }
public Nullable<system.datetime> BOD { get; set; }
public int DepartmentId { get; set; }
public bool Active { get; set; }
public virtual destDepartment destDepartment { get; set; }
}
And this is my action and i want change .First method because .First is used to find equivalent element (based on Id) in the orher list and i want to copy all data
public ActionResult Deploy()
{
List<srsEmployee> srsEmps = db.srsEmployees.ToList();
List<destEmployee> destEmps = db2.destEmployees.ToList();
db2.Database.ExecuteSqlCommand("TRUNCATE TABLE [destEmployees]");
foreach (var element in destEmps)
{
var oldValue = srsEmps.First(t => t.Id == element.Id);
element.Name = oldValue.Name;
element.EmpCode = oldValue.EmpCode;
element.Salary = oldValue.Salary;
element.StartDate = oldValue.StartDate;
element.BOD = oldValue.BOD;
element.DepartmentId = oldValue.DepartmentId;
element.Active = oldValue.Active;
}
foreach (var item in destEmps)
{
db2.destEmployees.Add(item);
}
db2.SaveChanges();
return View();
}
i want to copy data from srsEmps
to destEmps
using linq so if i have in srsEmps = {emp1,emp2,emp3}
i want to copy all those objects to destEmps
You can convert a class to another when your properties' names are same, just like your classes.
1) Download the nuget package "Automapper".
2) Create a your converter AutoMapperProfile class by using Profile class of Automapper package.
public class AutoMapperProfile : Profile
{
public AutoMapperProfile()
{
CreateMap<srsEmployee, destEmployee>();
}
}
3) Define the dependency in Application_Start in Global.asax.
Mapper.Initialize(x =>
{
x.AddProfile<AutoMapperProfile>();
});
4) Finally, you can convert list to another list.
List<srsEmployee> srsEmps = db.srsEmployees.ToList();
destEmps = srsEmps.Select(x => Mapper.Map<destEmployee>(x))
.ToList();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.