从一个SQL Azure表中提取数据,添加一列,然后填充另一个表

时间:2016-07-14 16:57:02

标签: c# linq azure azure-sql-database

我使用C#和LINQ来提取/推送SQL Azure中的数据。基本方案是我们有一个Customer表,其中包含所有客户(PK = CompanyID)和支持表,如LaborTypes和Materials(FK CompanyID到Customer表)。

当新客户注册时,会在Customers表中创建新记录。完成后,我想从一个单独的表中加载一组默认材料和laborTypes。如果我只想将数据直接从一个表复制到另一个表,但为了为新客户填充现有表,我很简单,我需要获取种子数据(例如,LaborType,laborDescription),为每行添加CompanyID种子数据,然后插入现有表。

使用C#和LINQ与SQL Azure实现此目的的最佳方法是什么?

下面是上下文引用的一个直接插入来自LaborTypes的用户输入的示例。

using (var context = GetContext(memCustomer))
{
   var u = GetUserByUsername(context, memUser);
   var l = (from lbr in context.LaborTypes
            where lbr.LaborType1.ToLower() == laborType
            && lbr.Company == u.Company
            select lbr).FirstOrDefault();

   if (l == null)
   {
      l = new AccountDB.LaborType();
      l.Company = u.Company;
      l.Description = laborDescription;
      l.LaborType1 = laborType;
      l.FlatRate = flatRate;
      l.HourlyRate = hourlyRate;
      context.LaborTypes.InsertOnSubmit(l);
      context.SubmitChanges();
   }
      result = true;
}

1 个答案:

答案 0 :(得分:0)

您要做的是编写一个从表B中检索数据的查询,并使用结果在表A上执行Insert语句。

This has been covered elsewhere in SO I think, here would be a good place to start

我不明白Linq的语法;但是通过构建类似于@Murph超出该链接的答案,我认为这可能有效。

var fromB= from b in TableB
           where ... ;//identify the row/data from table B
// you may need to make fromB populate from the DB here. 
var toInsert = ...; //construct your object with the desired data   
// do other necessary things here        
TableA.InsertAllOnSubmit(toInsert); 
dc.SubmitChanges(); // Submit your changes
相关问题