将数据从一个列表复制到另一个

时间:2018-10-17 16:38:27

标签: c# asp.net-mvc entity-framework linq

我有两个来自课程的列表srsEmpsdestEmps

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; }
 }

这是我的行动,我想更改.First方法,因为.First用于在orher列表中查找等效元素(基于ID),并且我想复制所有数据

       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();
    }

我想使用linq将数据从srsEmps复制到destEmps 因此,如果我有srsEmps = {emp1,emp2,emp3},我想将所有这些对象复制到destEmps

1 个答案:

答案 0 :(得分:0)

当属性的名称相同时,您可以将一个类转换为另一个类。

1)下载nuget软件包“ Automapper”。

2)使用Automapper程序包的Profile类创建一个转换器AutoMapperProfile类。

public class AutoMapperProfile : Profile
    {
        public AutoMapperProfile()
        {
            CreateMap<srsEmployee, destEmployee>();
        }
    }

3)在Global.asax的Application_Start中定义依赖项。

Mapper.Initialize(x =>
{
    x.AddProfile<AutoMapperProfile>();
});

4)最后,您可以将列表转换为另一个列表。

List<srsEmployee> srsEmps = db.srsEmployees.ToList();

destEmps  = srsEmps.Select(x => Mapper.Map<destEmployee>(x))
                   .ToList();