ASP.NET MVC viewmodel SQL query syntax - c#

I'm trying to convert basic models to model vİew and SQL queries. So what is wrong my queries or other files?
// GET: Cars
public ActionResult Index()
{
List<CarsTrxViewModel> model = db.Database.SqlQuery<CarsTrxViewModel>(SqlCars.CarsTrxByID()).ToList();
return View(model);
// return View(db.Cars.ToList());
}
View model:
public class CarsTrxViewModel
{
public int CarID { get; set; }
public string CarBrand { get; set; }
public string CarModel { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:mm:ss}")]
public DateTime CreateDate { get; set; }
}
Query:
public static class SqlCars
{
public static string CarsTrxByID()
{
return "select " + " * , " +
"cars.CarID as CarID " +
",cars.CarBrand as CarBrand " +
",cars.CarModel as CarModel " +
",cars.CreateDate as CreateDate " +
"from (SELECT * from [NagisOfflineDB].[dbo].[cars] )";
}
public static string GetCardholderByID()
{
return "SELECT TOP 1 * from [NagisOfflineDB].[dbo].[cars]";
}
}
Model:
public class Cars
{
[Key]
public int CarID { get; set; }
[StringLength(50)]
[Required]
public string CarBrand { get; set; }
[StringLength(250)]
[Required]
public string CarModel { get; set; }
public DateTime CreateDate { get; set; }
}
I'm not join or other operations I'm just select one column in one table and set alias rows so what is wrong my query?
Compiler say your query wrong its error System.Data.SqlClient.SqlException: 'Incorrect syntax near ')'.'
Full version of error
Server Error in '/' Application.
Incorrect syntax near ')'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near ')'.
Source Error:
Line 20:
Line 21:
Line 22: List model = db.Database.SqlQuery(SqlCars.CarsTrxByID()).ToList();
And the stack trace
[SqlException (0x80131904): Incorrect syntax near ')'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2552942
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5952492
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +285
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4169
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +58
System.Data.SqlClient.SqlDataReader.get_MetaData() +89
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted) +430
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest) +2598
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +1483
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +240
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) +14
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +402
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryInternal(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +266
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__68() +44
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.<>c__DisplayClass691.<ExecuteStoreQueryReliably>b__67() +167
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +190
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQueryReliably(String commandText, String entitySetName, ExecutionOptions executionOptions, Object[] parameters) +462
System.Data.Entity.Core.Objects.ObjectContext.ExecuteStoreQuery(String commandText, ExecutionOptions executionOptions, Object[] parameters) +60
System.Data.Entity.Internal.<>c__DisplayClass141.<ExecuteSqlQuery>b__13() +130
System.Data.Entity.Internal.LazyEnumerator1.MoveNext() +45
System.Collections.Generic.List1..ctor(IEnumerable1 collection) +387
System.Linq.Enumerable.ToList(IEnumerable1 source) +58
NgsOfflineDev.Controllers.CarsController.Index() in C:\Dev\NagisDevOffline\NgsOfflineDev\NgsOfflineDev\Controllers\CarsController.cs:22
lambda_method(Closure , ControllerBase , Object[] ) +61
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +58
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__4() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9874329
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159
Version Information:
Microsoft .NET Framework Version: 4.0.30319
ASP.NET Version: 4.7.3062.0

Related

.Net Application Breaks every time this page is accessed

This is the screenshot of the reoccurring error
whenever I connect my customerController to the database it shows this error. I am new to .net and was building this project. Could you please explain how to resolve this issue and what is the actual cause of it.
[![Stack Trace of Error](https://i.stack.imgur.com/ITLui.png)](https://i.stack.imgur.com/ITLui.png)
This is the CustomerController Class
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Vidly.Models;
using System.Data.Entity;
using IdentitySample.Models;
namespace Vidly.Controllers
{
public class CustomersController : Controller
{
private ApplicationDbContext _context;
public CustomersController()
{
_context = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
public ViewResult Index()
{
var customers = _context.Customers.ToList();
return View(customers);
}
}
}
This is the Customer class:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Vidly.Models
{
public class Customer
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
public bool isSubscribeToNewsLetter { get; set; }
public MembershipTypes MembershipType { get; set; }
public byte MembershipTypeId { get; set; }
}
}
Whenever I pass the reference of the customer class to the customer controller so that it can access the details of the customers stored there, then the error occurs.
But if I hardcode the same thing then it works perfectly. Currently my customer table has 2 customers, which I created using the code-first approach.
Edit:
The Full Stack Trace:
[SqlException (0x80131904): Cannot drop database "aspnet-MvcMovie" because it is currently in use.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +2585494 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +6038654
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +297
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +4477
System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) +997
System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +314 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +297 System.Data.Entity.Infrastructure.Interception.<>c.<NonQuery>b__4_0(DbCommand t, DbCommandInterceptionContext1 c) +12
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch(TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) +427
System.Data.Entity.SqlServer.<>c__DisplayClass57_0.b__0(DbConnection conn) +111
System.Data.Entity.SqlServer.<>c__DisplayClass60_0.b__0() +443
System.Data.Entity.SqlServer.<>c__DisplayClass2_0.b__0() +10
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func1 operation) +189 System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) +78 System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act) +175
System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) +552 System.Data.Entity.SqlServer.SqlProviderServices.DropDatabase(SqlConnection sqlConnection, Nullable1 commandTimeout, String databaseName) +317
System.Data.Entity.SqlServer.SqlProviderServices.DbDeleteDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +243 System.Data.Entity.Core.Common.DbProviderServices.DeleteDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) +76
System.Data.Entity.Core.Objects.ObjectContext.DeleteDatabase() +134
System.Data.Entity.Internal.DatabaseOperations.Delete(ObjectContext objectContext) +12
System.Data.Entity.Database.Delete() +222
System.Data.Entity.DropCreateDatabaseIfModelChanges1.InitializeDatabase(TContext context) +144 System.Data.Entity.Internal.<>c__DisplayClass66_01.b__0() +76
System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action) +60
System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization() +372
System.Data.Entity.Internal.<>c.b__58_0(InternalContext c) +9
System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) +129 System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action) +196
System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase() +86
System.Data.Entity.Internal.InternalContext.Initialize() +30
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
System.Data.Entity.Internal.Linq.InternalSet1.Initialize() +53 System.Data.Entity.Internal.Linq.InternalSet1.GetEnumerator() +15
System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +53 System.Collections.Generic.List1..ctor(IEnumerable1 collection) +174 System.Linq.Enumerable.ToList(IEnumerable1 source) +61 Vidly.Controllers.CustomersController.Index() in D:\C# and .Net\Practice\Vidly\Vidly\Controllers\CustomerController.cs:25 lambda_method(Closure , ControllerBase , Object[] ) +61
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +157 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor,IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c.b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass11_0.b__0() +58
System.Web.Mvc.Async.<>c__DisplayClass11_2.b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.b__1(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass3_6.b__4() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.b__1(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.<>c.b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c.b__151_2(IAsyncResult asyncResult, Controller controller) +13
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +22 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c.b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +29 System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9850389
System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163

DropDownList error during application run [duplicate]

This question already has answers here:
There is already an open DataReader associated with this Command which must be closed first
(19 answers)
Closed 5 years ago.
I have problem with DropDownList. When I run application via free hosting I have
Error: There is already an open DataReader associated with this
Command which must be closed first.
With information about source of error:
Line 51: #Html.DropDownList("ScreeningId", null, htmlAttributes: new { #class = "form-control" })
I add additionally files View and Controller:
public class ReservationsController : Controller
{
private AppDbContext db = new AppDbContext();
// GET: Reservations
public ActionResult Index()
{
return View(db.Reservations.ToList());
}
// GET: Reservations/Create
public ActionResult Create()
{
ViewBag.ScreeningId = new SelectList(db.Screenings, "Id", "Description");
HashSet<int> seats = new HashSet<int>(db.Reservations.Select(x => x.SeatNumber));
ViewBag.Seats = seats;
return View();
}
// POST: Reservations/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Id,FirstName,SecondName,Phone,SeatNumber,ScreeningId")] Reservation reservation)
{
ViewBag.ScreeningId = new SelectList(db.Screenings, "Id", "Description");
if (ModelState.IsValid)
{
// sprawdzamy czy miejsce bylo juz zajete
if (db.Reservations.Select(x => x.SeatNumber).Contains(reservation.SeatNumber))
{
return View(reservation);
}
else
{
db.Reservations.Add(reservation);
db.SaveChanges();
}
if (Session["Login"] != null)
{
return RedirectToAction("Index");
}
return RedirectToAction("Success");
}
return View(reservation);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
Part of View file
<div class="form-group">
#Html.LabelFor(model => model.Screening, "Seans", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ScreeningId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Screening, "", new { #class = "text-danger" })
</div>
</div>
[InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
Stack Trace
System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand command) +1545589
System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String method, SqlCommand command) +89
System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) +268
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) +118
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +64
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +161
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext`1 c) +9
System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch(TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed) +72
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) +356
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) +166
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +12
System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +37
[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) +112
System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +744
System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__6() +97
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +288
System.Data.Entity.Core.Objects.<>c__DisplayClass7.<GetResults>b__5() +154
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +189
System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +279
System.Data.Entity.Core.Objects.ObjectQuery`1.Execute(MergeOption mergeOption) +31
System.Data.Entity.Core.Objects.DataClasses.EntityReference`1.Load(MergeOption mergeOption) +139
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad() +333
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty(TItem propertyValue, String relationshipName, String targetRoleName, Boolean mustBeNull, Object wrapperObject) +87
System.Data.Entity.Core.Objects.Internal.<>c__DisplayClass7`2.<GetInterceptorDelegate>b__2(TProxy proxy, TItem item) +106
System.Data.Entity.DynamicProxies.Screening_333144174B6E44255ACF2CFB15F4499A880DB4ECDBA71E01178031C116125BB8.get_Film() +23
CinemaTicketReservation.Models.Screening.get_Description() +34
[TargetInvocationException: Property accessor 'Description' on object 'System.Data.Entity.DynamicProxies.Screening_333144174B6E44255ACF2CFB15F4499A880DB4ECDBA71E01178031C116125BB8' threw the following exception:'An error occurred while executing the command definition. See the inner exception for details.']
System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component) +378
System.Web.UI.DataBinder.GetPropertyValue(Object container, String propName) +87
System.Web.UI.DataBinder.Eval(Object container, String[] expressionParts) +86
System.Web.UI.DataBinder.Eval(Object container, String expression) +95
System.Web.Mvc.MultiSelectList.Eval(Object container, String expression) +35
System.Web.Mvc.<>c__DisplayClass2.<GetListItemsWithValueField>b__1(Object item) +86
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +164
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +387
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
System.Web.Mvc.MultiSelectList.GetListItemsWithValueField() +145
System.Web.Mvc.MultiSelectList.GetListItems() +44
System.Web.Mvc.MultiSelectList.GetEnumerator() +8
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +375
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
CinemaTicketReservation.Controllers.ReservationsController.Create() +248
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9987157
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I saw in some topics, that MARS (MultipleActiveResultSets=true) is needed here. I already add it, and still it's not working. Do you have some ideas?
This topic have reference to:
dropdownlist looks OK but not working [duplicate]
I can see architectural problems in your code.
You are calling the AppDbContext on the controller which is wrong and will result in a lot of errors. you have declared and instationated dbcontext on the ReservationsController but you are not disposing off the context after use.
Instead use an ApplicationService Class, and inject the interface on the controller. as such you can go to the ApplicationService class and use: using (AppDbContext db){return db.Reservations();} as such the context is disposed off.

Can't update a foreign key on an attached graph

I have an attached graph object and I can't figure out how to change the foreign key on a record. I have a Load record saved in my db. I retrieve said record by id with tracking on. I
public partial class Load
{
[Key]
public virtual int Id {get;set;}
[Required]
public virtual int AccountId { get; set; }
public virtual Account Account { get; set; }
[Required]
public virtual int CustomerId { get; set; }
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}
I then retrieve the customer record that I want to associate with the Load record
public partial class Customer
{
[Key]
public virtual int Id {get;set;}
[Required]
[MaxLength(100)]
public virtual string Name { get; set; }
}
No matter what I do, I get some sort of exception is thrown.
var customer = context.Customers.Where(x => x.Id == customerId).SingleOrDefault();
load.Customer = customer;
load.CustomerId = customer.Id;
load.ModifiedByApplicationUserId = userId;
load.ModifiedDateTime = DateTime.Now;
context.Entry(load).State = EntityState.Modified;
context.SaveChanges();
What is the proper way to go about changing the foreign key relationship on an attached graph object?
Edit. I have added the exception.
[InvalidOperationException: Attaching an entity of type 'Triton.Core.Models.Identity.ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.]
System.Data.Entity.Core.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet) +690
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach) +130
System.Data.Entity.Core.Objects.DataClasses.EntityReference.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach) +65
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach) +67
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach) +340
System.Data.Entity.Core.Objects.DataClasses.EntityReference1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach) +209
System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach) +164
System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity) +510
System.Data.Entity.Internal.Linq.<>c__DisplayClassa.<Attach>b__9() +97
System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +354
System.Data.Entity.Internal.Linq.InternalSet1.Attach(Object entity) +200
System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value) +357
System.Data.Entity.Infrastructure.DbEntityEntry1.set_State(EntityState value) +42
Triton.Service.LoadService.UpdateCustomer(Load load, Int32 customerId, Int32 userId) in d:\BitBucket\trunk\Triton\Triton.Service\LoadService.cs:73
Triton.Web.Controllers.LoadsController.Customer(LoadViewModel model) in d:\BitBucket\trunk\Triton\Triton.Web\Controllers\LoadsController.cs:138
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +434
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +60
System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
Castle.Proxies.AsyncControllerActionInvokerProxy.EndInvokeActionMethod_callback(IAsyncResult asyncResult) +42
Castle.Proxies.Invocations.AsyncControllerActionInvoker_EndInvokeActionMethod.InvokeMethodOnTarget() +103
Castle.DynamicProxy.AbstractInvocation.Proceed() +117
Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed() +48
Glimpse.Mvc.AlternateType.EndInvokeActionMethod.NewImplementation(IAlternateMethodContext context) +152
Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation) +183
Castle.DynamicProxy.AbstractInvocation.Proceed() +483
Castle.Proxies.AsyncControllerActionInvokerProxy.EndInvokeActionMethod(IAsyncResult asyncResult) +203
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass46.b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651688
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
It turned out I had an object in a sub class that was being referenced so EF was trying to add it to the graph. Once I nullified that object, everything worked properly.

Unable to fix 'The object cannot be deleted because it was not found in the ObjectStateManager.' [duplicate]

This question already has answers here:
The object cannot be deleted because it was not found in the ObjectStateManager
(10 answers)
Closed 8 years ago.
I am getting the following error when I try to delete an object from the datase using LINQ.
The object cannot be deleted because it was not found in the ObjectStateManager.
Note: When I try to run the query directly from the database, the object is deleted.
Code where I am getting the error:
public void deleteStorage(CommonLayer.TblNewsStorage storageToDelete)
{
using(DBTicketSystemEntities e = new DBTicketSystemEntities())
{
e.TblNewsStorage.DeleteObject(storageToDelete);
e.SaveChanges();
}
}
Stack Trace:
[InvalidOperationException: The object cannot be deleted because it was not found in the ObjectStateManager.]
System.Data.Objects.ObjectContext.DeleteObject(Object entity, EntitySet expectedEntitySet) +3061568
System.Data.Objects.ObjectSet`1.DeleteObject(TEntity entity) +18
DataLayer.DAStorage.deleteStorage(TblNewsStorage storageToDelete) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\DataLayer\DAStorage.cs:38
BusinessLayer.Storage.deleteStorage(String id) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\BusinessLayer\Storage.cs:43
NewsLibrary.Controllers.StorageController.Delete(TblNewsStorage storage) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\NewsLibrary\Controllers\StorageController.cs:61
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) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9688704
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Try sending the ID of the object you want to delete then query it inside your context instead of sending the whole object :
public void deleteStorage(int ID)
{
using(DBTicketSystemEntities e = new DBTicketSystemEntities())
{
//Like That
var selectedItem = e.TblNewsStorage.Where( t => t.ID == ID).FirstOrDefault();
e.TblNewsStorage.DeleteObject(selectedItem);
e.SaveChanges();
}
}
try below code:-
e.TblNewsStorage(storageToDelete).State = System.Data.EntityState.Deleted;
e.SaveChanges();
OR
e.TblNewsStorage.Attach(storageToDelete);
e.TblNewsStorage.Remove(storageToDelete);
e.SaveChanges();

Linq selecting from GroupBy

I want to select every group into custom class and every item into another custom class,
I done this like this:
_notificationsManager
.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.Select(g => new NotificationsGroupData {
Name = g.Key,
Notifications = g.Take(3).Select(s => new NotificationData {
Category = g.Key,
Text = s.Text,
Time = DateTime.Now.Subtract(s.Time)
})
})
Here the NotificationsGroupData:
public class NotificationsGroupData
{
public string Name { get; set; }
public IEnumerable<NotificationData> Notifications { get; set; }
}
And NotificationData:
public class NotificationData
{
public virtual TimeSpan Time { get; set; }
public virtual string Category { get; set; }
public virtual string Text { get; set; }
}
But when I'm trying to create loop over this I'm getting error:
The method or operation is not implemented.
On this line:
#foreach (var group in Model.Notifications)
How I can fix it?
Uodate:
I updated the code to this:
_notificationsManager.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.Select(g => new
{
Name = g.Key,
Notifications =
g.OrderBy(o => o.Time)
.Take(3)
.Select(s => new
{
Category = g.Key,
s.Text,
s.Time
})
}).AsEnumerable().Select(g => new NotificationsGroupData
{
Name = g.Name,
Notifications = g.Notifications
.Select(s => new NotificationData
{
Category = g.Name,
Text = s.Text,
Time = now - s.Time
})
})
And here the error:
The method or operation is not implemented.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NotImplementedException: The method or operation is not implemented.
Source Error: #foreach (var group in Model.Notifications)
Stack Trace:
[NotImplementedException: The method or operation is not implemented.] NHibernate.Linq.GroupBy.NonAggregatingGroupByRewriter.FlattenSubQuery(SubQueryExpression subQueryExpression, QueryModel queryModel) +608 NHibernate.Linq.GroupBy.NonAggregatingGroupByRewriter.ReWrite(QueryModel queryModel) +598 NHibernate.Linq.Visitors.QueryModelVisitor.GenerateHqlQuery(QueryModel queryModel, VisitorParameters parameters, Boolean root) +126 NHibernate.Linq.NhLinqExpression.Translate(ISessionFactoryImplementor sessionFactory) +208 NHibernate.Hql.Ast.ANTLR.ASTQueryTranslatorFactory.CreateQueryTranslators(String queryIdentifier, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 filters, ISessionFactoryImplementor factory) +51 NHibernate.Engine.Query.HQLExpressionQueryPlan.CreateTranslators(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) +100 NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, String collectionRole, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) +74 NHibernate.Engine.Query.HQLExpressionQueryPlan..ctor(String expressionStr, IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters, ISessionFactoryImplementor factory) +53 NHibernate.Engine.Query.QueryPlanCache.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow, IDictionary`2 enabledFilters) +320 NHibernate.Impl.AbstractSessionImpl.GetHQLQueryPlan(IQueryExpression queryExpression, Boolean shallow) +188 NHibernate.Impl.AbstractSessionImpl.CreateQuery(IQueryExpression queryExpression) +164 NHibernate.Linq.DefaultQueryProvider.PrepareQuery(Expression expression, IQuery& query, NhLinqExpression& nhQuery) +152 NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression)
+70 NHibernate.Linq.DefaultQueryProvider.Execute(Expression expression) +59 Remotion.Linq.QueryableBase`1.GetEnumerator() +128 System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +61 ASP._Page_Views_Layout_Notifications_cshtml.Execute() in d:\Dev\Projects\ADDE\ADDE\Views\Layout\Notifications.cshtml:21 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +88 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+291 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
+23 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
+22 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176 System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20()
+75 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99 System.Web.Mvc.Async.WrappedAsyncResult`1.End()
+50 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+31 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) +64 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) +1464
[HttpException (0x80004005): Error executing child request for 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) +3033503 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) +463 System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName) +35 ASP._Page_Views_Shared__Layout_cshtml.Execute() in d:\Dev\Projects\ADDE\ADDE\Views\Shared\_Layout.cshtml:33 System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197 System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +103 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +88 System.Web.WebPages.<>c__DisplayClass7.<RenderPageCore>b__6(TextWriter writer) +233 System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +10 System.Web.WebPages.WebPageBase.Write(HelperResult result) +71 System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +64 System.Web.WebPages.WebPageBase.PopContext() +246 System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +95 System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235 System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107 System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
+291 System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
+23 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +245 System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
+22 System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +176 System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20()
+75 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +99 System.Web.Mvc.Async.WrappedAsyncResult`1.End()
+50 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
+31 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
+9629708 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
I suspect the problem may well be in the DateTime.Now.Subtract(s.Time) part, possibly combined with your use of NotificationsGroupData.
I suggest you change your query to simply fetch all the data you need without processing it much, and then perform the more complex work locally using AsEnumerable. So something like:
// Use a single common idea of "now", don't re-evaluate each time
var now = DateTime.Now;
var query = _notificationsManager
.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.Select(g => new {
Name = g.Key,
Notifications = g.Take(3)
.Select(s => new {
Text = s.Text,
Time = s.Time
})
})
.AsEnumerable() // Force local evaluation for final step
.Select(g => new NotificationsGroupData {
Name = g.Name,
Notifications = g.Notifications
.Select(s => new NotificationData {
Category = g.Name,
Text = s.Text,
Time = now - s.Time
})
});
EDIT: Okay, as that's still giving problems, you could try doing everything post-grouping in-process:
var now = DateTime.Now;
var query = _notificationsManager
.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.AsEnumerable() // Force local evaluation for final step
.Select(g => new NotificationsGroupData {
Name = g.Key,
Notifications = g.Take(3)
.Select(s => new NotificationData {
Category = g.Key,
Text = s.Text,
Time = now - s.Time
})
});
Note that this is far from idea - it'll pull all the properties from the database, not just the ones you want. (And not just the first three - although "first" depends on the ordering too, which hasn't been specified anywhere that we can see.) It could be that this is one of those situations where you need to fall back to SQL, but it does sound like NHibernate could be doing more for you...
NHibernate cannot translate your query to sql. The quickest solution will be to make your selection statement on inmemory collection other than pass it to NHibernate. Try this:
_notificationsManager
.GetUserNotifications(_repositoryNotifications, _memberShipProvider)
.GroupBy(x => x.Category)
.ToList()
.Select(g => new NotificationsGroupData {
Name = g.Key,
Notifications = g.Take(3).Select(s => new NotificationData {
Category = g.Key,
Text = s.Text,
Time = DateTime.Now.Subtract(s.Time)
})
})
Another optin will be to write your query on HQL\SQL and pass it to NHibernate, so you'll have necessary number of data pulled from database and map it to your custom entities afterwards.

Categories

Resources