简体   繁体   English

C#linq:将行从一个表复制到另一个表

[英]C# linq : copy rows from a table to another table

I have 2 identical tables. 我有2个相同的表。 I want to copy some rows from the first table to the other. 我想将一些行从第一个表复制到另一个表。 This is what I have done: 这是我所做的:

var getTemplate = (from i in dc.Templates where i.Document == tablename select i );

            foreach (var val in getTemplate)
            {
                DAL.Type qt = new DAL.Type();

                qt.col1 = val.col1;
                qt.col2 = val.col2;
                ....
            }

But there are many columns. 但是有很多列。 Is there a way to copy the whole row at once? 有没有办法一次复制整行?

Christos is right, automapper is pretty much made for this type of thing. Christos是对的,automapper就是为这种事情而做的。 If you don't want to add the dependency to auto mapper or learn it then look at 如果您不想将依赖项添加到自动映射器或学习它,请查看

ConvertAll(). ConvertAll()。

https://msdn.microsoft.com/en-us/library/73fe8cwf(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/73fe8cwf(v=vs.110).aspx

I think Automapper will work. 我认为Automapper可以工作。 If your columns same name, you will get rid of big workload. 如果您的列名称相同,那么您将摆脱繁重的工作量。

You can convert like this; 您可以像这样转换;

BankViewModel bank = Mapper.Map<BankViewModel>(BankDto);

And your AutoMapper Initialization; 还有您的AutoMapper初始化;

    public class AutoMapping
    {
        internal static void Init()
        {
             Mapper.CreateMap<BankDto, BankViewModel>()
            .ForMember(dst => dst.Id, opt => opt.MapFrom(src => src.BankId))
            .ForMember(dst => dst.InstitutionBankId, opt => opt.MapFrom(src => src.InstitutionBankId));
        }
    }

Finally you should register your Inıtialization where Application Start in Global.asax. 最后,您应该在Global.asax中注册“应用程序从哪里开始”。

     protected void Application_Start()
     {
         AutoMapping.Init();
     }

If your columns same name Mapper.CreateMap<BankDto, BankViewModel>() will work. 如果您的列名称相同,则Mapper.CreateMap<BankDto, BankViewModel>()将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM