实体框架:'where子句

时间:2015-10-27 17:22:48

标签: c# asp.net-mvc entity-framework

我正在开发一个应用程序,概述当天在影院放映的电影。

我收到以下异常

  

'where子句

中的未知列'Extent2.Movie_ID'

这是引发异常的地方(额外的变量movies2,就像我为调试所做的那样):

public ActionResult MoviesToday()
{                
    var todaysDate = Convert.ToDateTime(DateTime.Now).Date;
    var showsToday = db.Shows.Where(s => s.StartTime.Year == todaysDate.Year && s.StartTime.Month == todaysDate.Month && s.StartTime.Day == todaysDate.Day);
    var movies = from firstItem in db.Movies
                 join secondItem in showsToday
                      on firstItem equals db.Movies.Where(x => x == secondItem.Movie).FirstOrDefault()
                 select firstItem;            
    movies = movies.Distinct();

    movies = movies.OrderBy(m => m.Name);
    var movies2 = movies.ToList(); // HERE THE EXCEPTION is THROWN
    return View(movies2);
}

这是我的Show模型类:

public class Show
{
        public int ID { get; set; }        
        public DateTime StartTime { get; set; }
        public string BookingLink { get; set; }
        public string StartTimeAsString { get; set; }

        public Movie Movie { get; set; }
        public Theater Theater { get; set; }
    }

你能看到什么错吗?

编辑:完整的异常详情+ stacktrace:

System.Data.Entity.Core.EntityCommandExecutionException was unhandled by user code
  HResult=-2146232004
  Message=An error occurred while executing the command definition. See the inner exception for details.
  Source=EntityFramework
  StackTrace:
       vid System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
       vid System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext context, ObjectParameterCollection parameterValues)
       vid System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__6()
       vid System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
       vid System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass7.<GetResults>b__5()
       vid System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
       vid System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption)
       vid System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0()
       vid System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
       vid System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       vid System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       vid CinemaWeb.Controllers.MoviesController.MoviesToday() i d:\Development\Cinema\CinemaWeb\Controllers\MoviesController.cs:rad 31
       vid lambda_method(Closure , ControllerBase , Object[] )
       vid System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
       vid System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
       vid System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
       vid System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
       vid System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
       vid System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
       vid System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
       vid System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult asyncResult, Object tag)
       vid System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
       vid System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d()
       vid System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f()
  InnerException: MySql.Data.MySqlClient.MySqlException
       HResult=-2147467259
       Message=Unknown column 'Extent2.Movie_ID' in 'where clause'
       Source=MySql.Data
       ErrorCode=-2147467259
       Number=1054
       StackTrace:
            vid MySql.Data.MySqlClient.MySqlStream.ReadPacket()
            vid MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)
            vid MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)
            vid MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)
            vid MySql.Data.MySqlClient.MySqlDataReader.NextResult()
            vid MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
            vid MySql.Data.Entity.EFMySqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
            vid System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
            vid System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c)
            vid System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
            vid System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext)
            vid System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior)
            vid System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
            vid System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior)
       InnerException: 

编辑3:我认为显然在Show和Movie之间设置映射的方式有问题,但我发现的例子建议我以这种方式实现它。为清楚起见,我想要一个节目有一部电影和一部剧院..

2 个答案:

答案 0 :(得分:1)

你的加入是“怪异的”。 equals如何评估someMovie == anotherMovie ??

你为什么不这样做:

var movies = (from
    s in db.Shows
where
    s.StartTime.Year == todaysDate.Year && 
    s.StartTime.Month == todaysDate.Month && 
    s.StartTime.Day == todaysDate.Day
select
    s.Movie).Distinct().ToList();

var shows = (from
    s in db.Shows
where
    s.StartTime.Year == todaysDate.Year && 
    s.StartTime.Month == todaysDate.Month && 
    s.StartTime.Day == todaysDate.Day
select
    s).ToList();

var shows = (from
    s in db.Shows.Include(x => x.Movies)
where
    s.StartTime.Year == todaysDate.Year && 
    s.StartTime.Month == todaysDate.Month && 
    s.StartTime.Day == todaysDate.Day
select
    s).ToList();

var movies = shows.Select(x => x.Movie).Distinct().ToList();

答案 1 :(得分:1)

我进行了搜索,发现了这个:Entity Framework 5 complex type and unknown column in field list error

副本: 默认情况下,EF需要复杂类型属性的列格式为{complextypename_propertyname}。如果您手动创建表并以不同方式命名列,则会出现不匹配。你可以尝试相应地重命名列(即street to address_street)并尝试它是否有效。或者,你应该能够在复杂类型的属性上添加一个属性,告诉EF不应该使用约定但是你指定的名称(例如[Column(&#34; street&#34;)]为street属性)。

此外,我建议您使用像&#34; Id&#34;在where子句中,我在比较两个对象时遇到了很多问题。

例: var movies =来自db.Movies中的firstItem                          在showsToday中加入secondItem                          on firstItem等于db.Movies.FirstOrDefault(x =&gt; x.ID == secondItem.Movie.ID)                          select firstItem;