EF code first Invalid column name

asp.net-mvc asp.net-mvc-3 entity-framework entity-framework-6

Question

I'm currently working on my own simple CMS using MVC to familiarize myself with MVC and EF.

At this time I've only got pages which can contain multiple paragraphs. In the database I've got 1 page (Home) and 1 paragraph.

On the index view of home I'm calling the GetParagraph action of my controller to get the paragraph based on the placeholder value. The placeholder value is being send correctly to the controller and the query. But I'm getting an exception when the query tries to access the database to retrieve the record.

Exception

{"Invalid column name 'ParagraphId'.\r\nInvalid column name 'PageId'.\r\nInvalid column name 'LinkUrl'.\r\nInvalid column name 'LinkText'.\r\nInvalid column name 'LinkTarget'.\r\nInvalid column name 'ImageUrl'.\r\nInvalid column name 'ImageLink'.\r\nInvalid column name 'ImageLinkTarget'.\r\nInvalid column name 'ImageAlt'."}

Models

    public class Page
        {
            [Key]
            public int PageId { get; set; }
            [DisplayName("Parent")]
            public int? ParentId { get; set; }
            [Required]
            public string Title { get; set; }
            [Required]
            [DisplayName("View name")]
            public string ViewName { get; set; }        
            [DataType(DataType.Date)]
            public DateTime Created = DateTime.Now;
            [Required]
            public bool Published { get; set; }

            public virtual ICollection<Paragraph> Paragraphs { get; set; }

        }
public class Paragraph
    {
        [Key]
        public int ParagraphId { get; set; }

        public int PageId { get; set; }
        public virtual Page Page { get; set; }
        public string Placeholder { get; set; }
        public string Title { get; set; }
        [AllowHtml]
        [DataType(DataType.MultilineText)]
        public string Text { get; set; } 
        public string LinkUrl { get; set; }
        public string LinkText { get; set; }
        public string LinkTarget { get; set; }
        public string ImageUrl { get; set; }
        public string ImageLink { get; set; }
        public string ImageLinkTarget { get; set; }
        public string ImageAlt { get; set; }        

        [DataType(DataType.Date)]
        public DateTime Created = DateTime.Now;

        [Required]
        public bool Published { get; set; }
    }

Controller

public class PzzlController : Controller
    {        
        PzzlDB _db = new PzzlDB();
        public ActionResult GetParagraph(string placeholder)
        {
            var viewModel = _db.Paragraphs.GetParagraphByPlaceholder(placeholder);
            if (viewModel != null)
            {
                return PartialView("~/Views/Shared/Pzzl/_Paragraph.cshtml", viewModel);
            }
            else
            {
                return null;
            }
        }

    }

Query

public static Paragraph GetParagraphByPlaceholder(
          this IQueryable<Paragraph> Paragraph, string placeholder)
        {
            try
            {

                return Paragraph.Single(p => p.Placeholder == placeholder);
            }
            catch (Exception)
            {
                return null;
            }
        }

Contents of Paragraph variable

Local = 'System.Linq.IQueryable<Pzzl.Models.Pzzl.Paragraph>' does not contain a definition for 'Local' and no extension method 'Local' accepting a first argument of type 'System.Linq.IQueryable<Pzzl.Models.Pzzl.Paragraph>' could be found (are you missing a using di...

Stacktrace

[SqlException (0x80131904): Invalid column name 'ParagraphId'.
Invalid column name 'PageId'.
Invalid column name 'LinkUrl'.
Invalid column name 'LinkText'.
Invalid column name 'LinkTarget'.
Invalid column name 'ImageUrl'.
Invalid column name 'ImageLink'.
Invalid column name 'ImageLinkTarget'.
Invalid column name 'ImageAlt'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +1753986
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5296058
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
   System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1682
   System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
   System.Data.SqlClient.SqlDataReader.get_MetaData() +90
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite) +1379
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +175
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
   System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.Entity.Infrastructure.Interception.<>c__DisplayClassb.<Reader>b__8() +69
   System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(Func`1 operation, TInterceptionContext interceptionContext, Action`1 executing, Action`1 executed) +93
   System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +320
   System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +240
   System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +104

[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
   System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +188
   System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +1283
   System.Data.Entity.Core.Objects.<>c__DisplayClass3.<GetResults>b__2() +185
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +499
   System.Data.Entity.Core.Objects.<>c__DisplayClass3.<GetResults>b__1() +271
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +251
   System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +600
   System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +89
   System.Lazy`1.CreateValue() +416
   System.Lazy`1.LazyInitValue() +152
   System.Lazy`1.get_Value() +75
   System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +40
   System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4078797
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__2(IEnumerable`1 sequence) +83
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +107
   System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +197
   System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +149
   System.Linq.Queryable.SingleOrDefault(IQueryable`1 source, Expression`1 predicate) +287
   Pzzl.Queries.Pzzl.ParagraphQueries.GetParagraphByPlaceholder(IQueryable`1 Paragraph, String placeholder) in C:\Projects\Speeltuin\MVCWebsite\Portfolio\Pzzl\Queries\Pzzl\ParagraphQueries.cs:43
   Portfolio.Controllers.PzzlController.GetParagraphTitle(String placeholder) in C:\Projects\Speeltuin\MVCWebsite\Portfolio\Portfolio\Controllers\PzzlController.cs:17
   lambda_method(Closure , ControllerBase , Object[] ) +180
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +214
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   Castle.Proxies.ControllerActionInvokerProxy.InvokeActionMethod_callback(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +47
   Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionMethod.InvokeMethodOnTarget() +226
   Castle.DynamicProxy.AbstractInvocation.Proceed() +117
   Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed() +48
   Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action) +195
   Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult) +198
   Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +45
   Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation) +183
   Castle.DynamicProxy.AbstractInvocation.Proceed() +483
   Castle.Proxies.ControllerActionInvokerProxy.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +235
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +253
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +21
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324
   System.Web.Mvc.Controller.ExecuteCore() +106
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +48
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +22
   System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +10
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +27
   System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +65
   System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +71
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1097

[HttpException (0x80004005): Fout bij uitvoeren van onderliggende aanvraagelement voor handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'.]
   System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +3122411
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage) +76
   System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +28
   System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm) +19
   System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter) +483
   System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, Object routeValues) +58
   ASP._Page_Views_Home_Index_cshtml.Execute() in c:\Projects\Speeltuin\MVCWebsite\Portfolio\Portfolio\Views\Home\Index.cshtml:10
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
   System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81
   System.Web.WebPages.StartPage.RunPage() +17
   System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
   System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
   System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +222
   System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
   Castle.Proxies.Invocations.IView_Render.InvokeMethodOnTarget() +188
   Castle.DynamicProxy.AbstractInvocation.Proceed() +117
   Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed() +48
   Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action) +195
   Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult) +198
   Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +45
   Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation) +183
   Castle.DynamicProxy.AbstractInvocation.Proceed() +483
   Castle.Proxies.IViewProxy.Render(ViewContext viewContext, TextWriter writer) +202
   System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +295
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
   Castle.Proxies.ControllerActionInvokerProxy.InvokeActionResult_callback(ControllerContext controllerContext, ActionResult actionResult) +39
   Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionResult.InvokeMethodOnTarget() +182
   Castle.DynamicProxy.AbstractInvocation.Proceed() +117
   Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed() +48
   Glimpse.Core.Extensibility.ExecutionTimer.Time(Action action) +195
   Glimpse.Core.Extensions.AlternateMethodContextExtensions.TryProceedWithTimer(IAlternateMethodContext context, TimerResult& timerResult) +198
   Glimpse.Core.Extensibility.AlternateMethod.NewImplementation(IAlternateMethodContext context) +45
   Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation) +183
   Castle.DynamicProxy.AbstractInvocation.Proceed() +483
   Castle.Proxies.ControllerActionInvokerProxy.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +219
   System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
   System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +21
   System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +324
   System.Web.Mvc.Controller.ExecuteCore() +106
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +91
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +48
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9628972
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Accepted Answer

I still haven't figured out what's causing my problem, so I've started over using migrations from the get go. So far I haven't encountered this issue again.


Popular Answer

Did you check the obvious things like your connectionstring(s)? If you have more than one connection string it might be worth checking that's it's not referring to a local MSSQL-express database instead of another (perhaps online) database.

It looks like your using the EF code first principle. So it could be that it has to do with your database not being up-to-date, or atleast that your model thinks it isn't. You can use migrations for this, see this link for more information.

Though in the last case I certainly would expect a different error message.

Hope this helps..




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why