如何在LINQ中使用变量值实体

时间:2013-08-05 09:10:23

标签: linq entity-framework

这是我的代码

if (Count < LeaveTypeCount)
{
    for (int i = 0; i < LeaveTypeCount; i++)
    {
        var LeaveId = from l in CompObj.LeaveTypes
                      select l.LeaveID;
       var leaveIdArray = LeaveId.ToArray ();

        var LeaveDefault = (from c in CompObj.LeaveTypes
                            where (c.LeaveID ==leaveIdArray[i])
                            select new { c.DefaultLeave }).FirstOrDefault();

        Int32 DefaultCount = Convert.ToInt32(LeaveDefault.DefaultLeave);


        AssignedLeave AddObj = new AssignedLeave();
        AddObj.EmpID = EmpID;
        AddObj.AssignedYear = LeaveYear;
        AddObj.LeaveID =leaveIdArray[i];
        AddObj.TotalLeave = DefaultCount;
        CompObj.AssignedLeaves.AddObject(AddObj);
        CompObj.SaveChanges();

    }
}

但显示错误 LINQ to Entities不支持LINQ表达式节点类型'ArrayIndex'。

如何解决此问题或执行此任务的另一种方法

由于

1 个答案:

答案 0 :(得分:0)

您只需要将值复制到本地变量:

   var leaveIdValue = leaveIdArray[i];

    var LeaveDefault = (from c in CompObj.LeaveTypes
                        where (c.LeaveID ==leaveIdValue)
                        select new { c.DefaultLeave }).FirstOrDefault();
顺便说一下,您应该将leaveIdArray移出循环,因为它不依赖于i的值。