2013-11-21 51 views
1

林困難與linq查詢。見下文。Linq到實體[無法創建類型'...'的常量值]

var userHelper = new UserHelper(dbContext); 

var currentUser = (from u in dbContext.Users 
        where u.UserID == request.VTIUser.UserID 
        select u).SingleOrDefault(); 

var userIds = (from u in dbContext.Users 
       from r in dbContext.OrgRanges 
       select u.UserID).ToList(); 

只有一個條款,它工作正常。

異常消息

無法創建類型的恆定值 'VTI.Entities.OrgRange'。在此上下文中僅支持基本類型(如Int32,String和Guid)。

堆棧跟蹤

at System.Data.Objects.ELinq.ExpressionConverter.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.NewArrayInitTranslator.<>c__DisplayClass77.<TypedTranslate>b__75(Expression e) 
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext() 
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator`3.Validate(IEnumerable`1 argument, String argumentName, Int32 expectedElementCount, Boolean allowEmpty, Func`3 map, Func`2 collect, Func`3 deriveName) 
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.EnumerableValidator`3.Validate() 
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.CreateExpressionList(IEnumerable`1 arguments, String argumentName, Boolean allowEmpty, Action`2 validationCallback) 
at System.Data.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateNewCollection(IEnumerable`1 elements, DbExpressionList& validElements) 
at System.Data.Objects.ELinq.ExpressionConverter.NewArrayInitTranslator.TypedTranslate(ExpressionConverter parent, NewArrayExpression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.ConstantTranslator.TypedTranslate(ExpressionConverter parent, ConstantExpression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input) 
at System.Data.Objects.ELinq.ExpressionConverter.TranslateLambda(LambdaExpression lambda, DbExpression input, DbExpressionBinding& binding) 
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.OneLambdaTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, DbExpression& source, DbExpressionBinding& sourceBinding, DbExpression& lambda) 
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SelectManyTranslator.Translate(ExpressionConverter parent, MethodCallExpression call) 
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.SequenceMethodTranslator.Translate(ExpressionConverter parent, MethodCallExpression call, SequenceMethod sequenceMethod) 
at System.Data.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TypedTranslator`1.Translate(ExpressionConverter parent, Expression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq) 
at System.Data.Objects.ELinq.ExpressionConverter.Convert() 
at System.Data.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption) 
at System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) 
at System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() 
at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() 
at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() 
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) 
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) 
at CrewSheetWebService.Controllers.UsersController.GetUsers() in c:\Users\patrich.ISCDEVELOPMENT\Documents\Visual Studio 2010\WebSites\St Paul\App_Code\WebAPI\Controllers\UsersController.cs:line 53 
at lambda_method(Closure , Object , Object[]) 
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object instance, Object[] methodParameters) 
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) 
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.<>c__DisplayClass5.<ExecuteAsync>b__4() 
at System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func`1 func, CancellationToken cancellationToken) 

用戶模型

[Table("tblUsers")] 
    public class User 
    { 
    [Key] 
    public int UserID { get; set; } 

    [StringLength(10)] 
    public string EmpNumber { get; set; } 

    [StringLength(10)] 
    public string Appointment { get; set; } 

    [StringLength(6)] 
    public string OrgLevel1 { get; set; } 

    [StringLength(6)] 
    public string OrgLevel2 { get; set; } 

    [StringLength(6)] 
    public string OrgLevel3 { get; set; } 

    [StringLength(200)] 
    public string EmpName { get; set; } 

    [StringLength(200)] 
    public string Email { get; set; } 

    [StringLength(15)] 
    public string Phone { get; set; } 

    public DateTime HireDate { get; set; } 

    [StringLength(50)] 
    public string Password { get; set; } 

    public int? Supervisor { get; set; } 

    public int? Role { get; set; } 

    public int? PayCycleID { get; set; } 

    public int DocumentGroupID { get; set; } 

    public DateTime EffectedDate { get; set; } 

    public DateTime ExpirationDate { get; set; } 

    public int? GroupID { get; set; } 

    public int? EmpPosition { get; set; } 

    public int? EmpStatus { get; set; } 

    public int PunchID { get; set; } 

    [ForeignKey("PunchID")] 
    public virtual PunchProfile PunchProfile { get; set; } 

    [StringLength(50)] 
    public string ADUserID { get; set; } 

    [StringLength(10)] 
    public string Pin { get; set; } 

    [StringLength(10)] 
    public string Union1 { get; set; } 

    [StringLength(10)] 
    public string Union2 { get; set; } 

    [StringLength(10)] 
    public string Union3 { get; set; } 

    public decimal? HourlyRate { get; set; } 

    public int? PayType { get; set; } 

    public int? FLSAProfile { get; set; } 

    public int? FMLVProfile { get; set; } 

    public int? PercentFullTime { get; set; } 

    public DateTime? LastModified { get; set; } 

    public virtual ICollection<UserJob> UserJobs { get; set; } 

    public virtual ICollection<UserSkill> UserSkills { get; set; } 

    public virtual ICollection<UserSchedule> UserSchedules { get; set; } 

    public virtual ICollection<UserRange> Ranges { get; set; } 

    public static UserSchedule GetCurrentUserSchedule(IList<UserSchedule> userScheds) 
    { 
     return userScheds.Where(us => DateTime.Now.IsBetween(us.StartDate, us.EndDate)).FirstOrDefault(); 
    } 

    public User() 
    { 
    } 

    public bool HasRole(int role) 
    { 
     return (Role & role) == role; 
    } 
    } 

OrgRange模型

[Table("tblOrgRanges")] 
    public class OrgRange 
    { 
    [Key] 
    public int RangeID { get; set; } 

    public int GroupID { get; set; } 

    [ForeignKey("GroupID")] 
    public virtual Group Group { get; set; } 

    [StringLength(30)] 
    public string RangeName { get; set; } 

    [StringLength(100)] 
    public string RangeDescription { get; set; } 

    [StringLength(6)] 
    public string OrgLevel1Min { get; set; } 

    [StringLength(6)] 
    public string OrgLevel1Max { get; set; } 

    [StringLength(6)] 
    public string OrgLevel2Min { get; set; } 

    [StringLength(6)] 
    public string OrgLevel2Max { get; set; } 

    [StringLength(6)] 
    public string OrgLevel3Min { get; set; } 

    [StringLength(6)] 
    public string OrgLevel3Max { get; set; } 

    public DateTime EffectiveDate { get; set; } 

    public DateTime ExpirationDate { get; set; } 

    // Don't use this function in a LINQ Where clause. It won't work. 
    public bool Include(string orgLevel1, string orgLevel2, string orgLevel3) 
    { 
     return (OrgLevel1Min.CompareTo(orgLevel1) <= 0 && OrgLevel1Max.CompareTo(orgLevel1) >= 0) 
     && (OrgLevel2Min.CompareTo(orgLevel2) <= 0 && OrgLevel2Max.CompareTo(orgLevel2) >= 0) 
     && (OrgLevel3Min.CompareTo(orgLevel3) <= 0 && OrgLevel3Max.CompareTo(orgLevel3) >= 0); 
    } 

    public OrgRange() 
    { 
    } 
    } 
+0

你可以發佈'User'和'OrgRange'模型類嗎? –

回答

1

的問題是,實體框架不知道如何將實體轉化爲SQL 。我在你提供的代碼中找不到這個問題,但我想你可以通過下面的例子找到有問題的代碼。

var user = GetUserById(42); 

var orders = context.Orders.Where(order => order.Customer == customer); 

這將失敗,因爲實體框架不知道怎麼翻譯兩個用戶實體的比較到SQL。要解決這個問題,你必須使用主鍵比較重寫這個。

var user = GetUserById(42); 

var orders = context.Orders.Where(order => order.Customer.Id == customer.Id); 

這將工作,因爲實體框架現在可以看到ID和整數的比較,並且可以將其轉換爲SQL語句。我總是想知道爲什麼實體框架不能自行執行這種重寫,只是用主鍵的比較來替換所有實體的比較,但可能存在我不知道的邊界情況。

+1

丹尼爾布魯克納:謝謝。我明白你給的例子。我的代碼不會做實體比較。 from語句單獨運行良好。鏈接一個接一個時會發生此錯誤。 –

+0

我嘗試了一個簡單的例子,像你這樣的查詢對我來說工作得很好。我仍然不相信你提到的問題是問題的真正原因;也許實際的原因是查詢的副作用。你能提供更多的代碼圍繞UsersController.cs第53行嗎?當您檢索的唯一東西是其中一個實體的ID時,您爲什麼首先進行交叉連接? –

+0

我在有問題的代碼之前添加了兩行代碼。這是該功能的開始。爲currentUser分配一個值的行不會出錯。 –

相關問題