返回LINQ查询和INSERT数据

时间:2016-02-09 18:38:04

标签: c# sql-server linq asp.net-web-api2

我需要从表(Job)中获取数据并将该数据复制到另一个表(JobDetails)上的相应列中。我正在运行LINQ查询,该查询从(Job)表中获取数据,我需要在此处插入JobDetails表中:

 //Run query to get a list of all tasks that have the group ID passed
        IQueryable<Task> TasksQuery =
            from c in db.Tasks
            select c;
    //Execute and loop results...
    IQueryable<Task> TasksByGroupId = TasksQuery.Where(c => c.TaskGroupId == TasksGroupId);

    //TODO: Insert the results or list from above as a new JobDetails row

现在,在提取此数据并将其插回到JobDetails表的特定列中时,我完全失败了。我尝试过.ToList()尝试创建一个可读的列表,但我确信有更有效的方法可以做到这一点。我希望能够一次分配一个列并将其插入到JobDetails表的相应行中。

编辑:已添加课程

public partial class Job
{
    public int Id { get; set; }
    public System.DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }
    public Nullable<System.DateTime> ClosedDate { get; set; }
    public string ClosedBy { get; set; }
    public string Revision { get; set; }
}

public partial class JobDetail
{
    public int Id { get; set; }
    public int JobId { get; set; }
    public Nullable<int> TaskId { get; set; }
    public Nullable<int> TaskIdOrder { get; set; }
    public System.DateTime TimeCompleted { get; set; }
    public string CompletedBy { get; set; }
    public string Revision { get; set; }
}

编辑:添加了任务类

public partial class Task

{
    public int Id { get; set; }
    public string TaskName { get; set; }
    public string TaskDescription { get; set; }
    public int TaskGroupId { get; set; }
    public int TaskOrder { get; set; }
}

1 个答案:

答案 0 :(得分:1)

foreach (var task in TasksByGroupId)
{
    db.JobDetails.AddObject(new JobDetail()
        {
            TaskId = task.Id,
            TaskIdOrder = task.TaskOrder
        });
}

db.SaveChanges();