I m building an mvc application, using EF code first. I m right at begning. here is code which is concerned with my problem.
Advertisement Model
[Key]
public virtual int ID { get; set; }
public virtual int UserID { get; set; }
public virtual int Cycles { get; set; }
public virtual decimal Cost { get; set; }
public string Name { get; set; }
public virtual List<AdDisplayTime> DispalyTime { get; set; }
public virtual DateTime CreateDate { get; set; }
public virtual DateTime UpdateDate { get; set; }
public virtual int UpdatedBy { get; set; }
public virtual bool FullScreen { get; set; }
AdDisplayTimes Model
[Key]
public virtual int ID { get; set; }
public virtual int AdID { get; set; }
public virtual string DisplayTime { get; set; }
Status Model
[Key]
public virtual int ID { get; set; }
public virtual string Name { get; set; }
Here is seed method in my migrations class
var adDisplayTimes = new List<AdDisplayTime>
{
new AdDisplayTime{AdID = 1,DisplayTime = "10:30"},
new AdDisplayTime{AdID = 1,DisplayTime = "10:40"},
new AdDisplayTime{AdID = 1,DisplayTime = "10:50"},
new AdDisplayTime{AdID = 1,DisplayTime = "11:00"}
};
context.Advertisements.AddOrUpdate(a => a.Name,
new Advertisement
{
Name = "Fisrt Ad",
OwnerID = 1,
Cycles = 125,
Cost = (decimal)234.45,
FileName = "test.jpg",
Tier = 1,
Path = "~/UploadedImages/Pending/test.jpg",
DispalyTime = adDisplayTimes,
CreateDate = DateTime.Now,
ValidFrom = DateTime.Now,
ValidTill = DateTime.Now.AddMonths(1),
FullScreen = true,
IsAdminAd = false,
Status = 1
}
);
context.AdDisplayTimes.AddOrUpdate(ad=>ad.AdID,
new AdDisplayTime { AdID = 1, DisplayTime = "10:30" },
new AdDisplayTime { AdID = 1, DisplayTime = "10:40" },
new AdDisplayTime { AdID = 1, DisplayTime = "10:50" },
new AdDisplayTime { AdID = 1, DisplayTime = "11:00" }
);
context.Statuses.AddOrUpdate(s=>s.Name,
new Status{Name = "Pending"},
new Status{Name = "Approved"},
new Status{Name = "Edited"},
new Status{Name = "Activated"},
new Status{Name = "DeActivated"}
);
When i run command "update-database" from package manager consol in Visual studio I get
this
update-database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
No pending code-based migrations.
Running Seed method.
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
--- End of inner exception stack trace ---
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at System.Data.Entity.Migrations.DbMigrator.SeedDatabase()
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.SeedDatabase()
at System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.Infrastructure.MigratorLoggingDecorator.Upgrade(IEnumerable`1 pendingMigrations, String targetMigrationId, String lastMigrationId)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration)
at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.RunCore()
at System.Data.Entity.Migrations.Design.ToolingFacade.BaseRunner.Run()
An error occurred while updating the entries. See the inner exception for details.
Please help me solve this
if you check inner exception you can see this error
The conversion of a datetime2 data type to a datetime data
type resulted in an out-of-range value
and the common solution found in SO is defining DateTime column's data type as datetime2.you can do it with Data Annotation like :
[Column(TypeName="datetime2")]
and with Fluent Api like :
HasColumnType("datetime2")
hope this helps.
Related
I'm trying to delete a record in the database by simply using db.'table'.remove('object') but when calling db.SaveChanges() exception is thrown.
'An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code'
My deleting method in controller
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Customer customer = db.Customers.Find(id);
if (customer == null)
{
return HttpNotFound();
}
db.Customers.Remove(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
Model:
public class Customer
{
[Key, ForeignKey("User")]
public int UserId { get; set; }
public string Email { get; set; }
public virtual CreditCard CreditCard { get; set; }
public virtual ShoppingCart ShoppingCart { get; set; }
public virtual List<Enquiry> Enquiries { get; set; }
public virtual List<Order> Orders { get; set; }
public virtual User User { get; set; }
}
public class User
{
[Key]
public int Id { set; get; }
public string Username { set; get; }
public string Password { set; get; }
public string FirstName { set; get; }
public string Surname { set; get; }
public virtual UserRole UserRole { get; set; }
}
public class ShoppingCart
{
[Key, ForeignKey("Customer")]
public int Id { get; set; }
public virtual List<CartItem> CartItems { get; set; }
public virtual Customer Customer { get; set; }
}
Part of the exception:
A DbUpdateException was caught while saving changes. Type: Customer_8D9A6B7F7D247C9CB9F95E830039791E299E94FC91841FD33610DD1804AEF739 was part of the problem.
Full exception:
System.Data.Entity.Infrastructure.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.Entity.Core.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.ShoppingCarts_dbo.Customers_Id". The conflict occurred in database "MVC_COMP1562.Models.SchemaDBContext", table "dbo.ShoppingCarts", column 'Id'.
The statement has been terminated.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption)
at 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)
at 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)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext`1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher`1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func`3 operation, TInterceptionContext interceptionContext, Action`3 executing, Action`3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteNonQuery()
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
--- End of inner exception stack trace ---
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.<Update>b__2(UpdateTranslator ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T noChangesResult, Func`2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.<SaveChangesInternal>b__27()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
--- End of inner exception stack trace ---
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at MVC_COMP1562.Controllers.CustomersController.Delete(Nullable`1 id) in C:\Users\kacpe\Documents\Visual Studio 2015\Projects\MVC_COMP1562\MVC_COMP1562\Controllers\CustomersController.cs:line 165
It seems you have another Table called dbo.ShoppingCarts about a Shopping Cart, which have one or more rows related to the Customer you are trying to delete.
So first you must delete the rows related to that customer an then you can delete the customer. That happens because the Customer id is foreign key in that other table.
If that is no exactly the case, please add your ShoppingCarts class to the question.
I seem to be getting DbUpdateException error on db.SaveChanges() after I edit my Delivery or Order. I'm not sure why, it works fine for Create and Delete.
Am I missing something somewhere? The GET Edit methods work fine for both.
I get this exception error:
System.Data.Entity.Infrastructure.DbUpdateException was unhandled by
user code HResult=-2146233087 Message=An error occurred while
updating the entries. See the inner exception for details.
Source=EntityFramework StackTrace:
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at HealthHabitat.Controllers.DeliveryController.Edit(DeliveryVM model) in c:\Users\Luffy\Desktop\HealthHabitat
V25\HealthHabitat\Controllers\DeliveryController.cs:line 172
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary2
parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.ActionInvocation.InvokeSynchronousActionMethod()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult
asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult
asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Async.AsyncResultWrapper.End[TResult](IAsyncResult
asyncResult, Object tag)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult
asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
InnerException: System.Data.Entity.Core.UpdateException
HResult=-2146233087
Message=An error occurred while updating the entries. See the inner exception for details.
Source=EntityFramework
StackTrace:
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.b__2(UpdateTranslator
ut)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update[T](T
noChangesResult, Func2 updateFunction)
at System.Data.Entity.Core.EntityClient.Internal.EntityAdapter.Update()
at System.Data.Entity.Core.Objects.ObjectContext.<SaveChangesToStore>b__35()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1
func, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions
options, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass2a.b__27()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1
operation)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions
options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions
options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
InnerException: System.Data.SqlClient.SqlException
HResult=-2146232060
Message=The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value. The statement
has been terminated.
Source=.Net SqlClient Data Provider
ErrorCode=-2146232060
Class=16
LineNumber=1
Number=242
Procedure=""
Server=(LocalDb)\v11.0
State=3
StackTrace:
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at System.Data.SqlClient.SqlDataReader.get_MetaData()
at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString)
at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader
ds)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method)
at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.b__c(DbCommand
t, DbCommandInterceptionContext1 c)
at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget
target, Func3 operation, TInterceptionContext interceptionContext,
Action3 executing, Action3 executed)
at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
command, DbCommandInterceptionContext interceptionContext)
at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.Entity.Core.Mapping.Update.Internal.DynamicUpdateCommand.Execute(Dictionary2
identifierValues, List`1 generatedValues)
at System.Data.Entity.Core.Mapping.Update.Internal.UpdateTranslator.Update()
InnerException:
Order Controller POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "OrderID,HospitalID,StaffID,Date,Time,Expected_Date")] Order order)
{
if (ModelState.IsValid)
{
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = order.OrderID });
}
//ViewBag.DeliveryID = new SelectList(db.Deliverys, "DeliveryID", "DeliveryID", order.DeliveryID);
ViewBag.HospitalID = new SelectList(db.Hospitals, "HospitalID", "Name", order.HospitalID);
ViewBag.StaffID = new SelectList(db.Staffs, "StaffID", "First_Name", order.StaffID);
return View(order);
}
Delivery Controller POST:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(DeliveryVM model)
{
Delivery delivery = new Delivery()
{
DriverID = model.DriverID,
};
db.Deliverys.Add(delivery);
db.SaveChanges();
// save the selected orders based on the ID of the Delivery object
IEnumerable<int> selectedOrders = model.Orders.Where(o => o.IsSelected).Select(o => o.ID);
foreach (int ID in selectedOrders)
{
Order order = db.Orders.Where(o => o.OrderID == ID).FirstOrDefault();
order.DeliveryID = delivery.DeliveryID;
db.Entry(order).State = EntityState.Modified;
}
db.SaveChanges();
return RedirectToAction("Details", new { id = delivery.DeliveryID });
Order Model:
public int OrderID { get; set; }
[Display(Name = "Hospital")]
public int HospitalID { get; set; }
[Display(Name = "Staff")]
public int StaffID { get; set; }
public int? DeliveryID { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
public DateTime Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Expected_Date { get; set; }
public virtual Hospital Hospital { get; set; }
public virtual Staff Staff { get; set; }
public virtual Delivery Delivery { get; set; }
public virtual ICollection<OrderItem> OrderItems { get; set; }
Delivery Model:
public enum Status
{
Dispatched, Delayed, Delivered
}
public class Delivery
{
public int DeliveryID { get; set; }
[Display(Name = "Driver")]
public int DriverID { get; set; }
public Status Status { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Comment { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Dispatched")]
public DateTime Dispatched_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Dispatched")]
public DateTime Dispatched_Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Delivered")]
public DateTime? Delivered_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Delivered")]
public DateTime? Delivered_Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Delayed")]
public DateTime? Delayed_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Delayed")]
public DateTime? Delayed_Time { get; set; }
public virtual Driver Driver { get; set; }
public virtual ICollection<Order> Orders { get; set; }
}
ViewModels:
public enum Status
{
Dispatched, Delayed, Delivered
}
public class DeliveryVM
{
public int? ID { get; set; }
public int DriverID { get; set; }
public Status Status { get; set; }
[DisplayFormat(ConvertEmptyStringToNull = false)]
public string Comment { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Dispatched")]
public DateTime Dispatched_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Dispatched")]
public DateTime Dispatched_Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Delivered")]
public DateTime? Delivered_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Delivered")]
public DateTime? Delivered_Time { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Date Delayed")]
public DateTime? Delayed_Date { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString = "{0:HH:mm}", ApplyFormatInEditMode = true)]
[Display(Name = "Time Delayed")]
public DateTime? Delayed_Time { get; set; }
public SelectList DriverList { get; set; }
public List<OrderVM> Orders { get; set; }
}
public class OrderVM
{
public int ID { get; set; }
public string Name { get; set; }
public string Address_1 { get; set; }
public string Address_2 { get; set; }
public string Address_3 { get; set; }
public string Province { get; set; }
public DateTime Date { get; set; }
public int DeliveryID { get; set; }
public bool IsSelected { get; set; }
}
PLEASE NOTE: I didn't use ViewModels for Edit Order, only for Edit Delivery.
The important part of the error is
Message=The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value`.
Both Delivery and Order have a number of DateTime fields and at least one of them is not being set when you save so their values are 01/01/0001 (i.e. DateTime.MinValue), but your database table field is DATETIME which only has a year range of 1753-9999. To prevent the error, you can change the sql type to DATETIME2 which matches the c# DateTime range.
However, I suspect the real issue is that you really should be setting the DateTime property. Your Edit() POST method has
Delivery delivery = new Delivery()
{
DriverID = model.DriverID,
};
db.Deliverys.Add(delivery);
however an Edit() method suggests your editing and existing object, so it should be
// Get the data model based on the ID of the view model
Delivery delivery = db.Delivery.Find(model.ID);
// Map the view model properties to the data model
delivery.DriverID = model.DriverID;
// Mark as modified and save
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();
Please don't mark this as DUPLICATE QUESTION.
I've been trying to do follow all the answers I have found but I still get this error. Can anyone give me idea where this error came from ??
Here's the error
Server Error in '/NomsPR' Application.
Specified cast is not valid.
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.InvalidCastException: Specified cast is not valid.
Source Error:
Line 36: while (reader.Read())
Line 37: {
Line 38: results.Add( new NomsPRItem()
Line 39: {
Line 40: RequestID = reader.GetInt32(0)
Source File: c:\SVN\branches\NomsPRMonitoring\NomsPRMonitoring\Models\CheckerConnection.cs Line: 38
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Int32() +6639748
Lear.NomsPRMonitoring.Models.CheckerConnection.LoadPRItems(DateTime from, DateTime to) in c:\SVN\branches\NomsPRMonitoring\NomsPRMonitoring\Models\CheckerConnection.cs:38
Lear.NomsPRMonitoring.Controllers.CheckerController.GetList() in c:\SVN\branches\NomsPRMonitoring\NomsPRMonitoring\Controllers\CheckerController.cs:33
lambda_method(Closure , ControllerBase , Object[] ) +79
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +261
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +34
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +124
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +838499
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +33
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +839052
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +65
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +51
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +15
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +51
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
Here is my model :
public class NomsPRItem
{
public long RequestID { get; set; }
public long PartID { get; set; }
public string PartNumber { get; set; }
public string PartDesc { get; set; }
public string UnitName { get; set; }
public double PartQuantity { get; set; }
public string CurrName { get; set; }
public double PiecePrice { get; set; }
public DateTime DeliveryDate { get; set; }
public string ProposeSuppliers { get; set; }
public string Comments { get; set; }
public long AccountTypeID { get; set; }
public string AccountType { get; set; }
public string InboxLearUID { get; set; }
public bool ReviewFlag { get; set; }
public long SubCatID { get; set; }
public string SubCatName { get; set; }
public DateTime CreateDate { get; set; }
public string CreateBy { get; set; }
public DateTime LastDate { get; set; }
public string LastBy { get; set; }
public string SupplierID { get; set; }
public string CostCenter { get; set; }
public long SubAccountTypeID { get; set; }
public string SubAccountType { get; set; }
public double TotalAmount { get; set; }
public double Amount { get; set; }
public string ItemId { get; set; }
public string FullName { get; set; }
}
}
And my connection
public static List<NomsPRItem> LoadPRItems(DateTime from, DateTime to)
{
string sSrcipt = m_sReport + "and p.[RequestDate] between '" + from.ToString("yyyy-MM-dd HH:mm:ss") + "' and '" + to.ToString("yyyy-MM-dd HH:mm:ss") + "'";
List<NomsPRItem> results = new List<NomsPRItem>();
using (SqlConnection con = new SqlConnection(m_sConnectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand(sSrcipt, con))
{
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
results.Add( new NomsPRItem()
{
RequestID = reader.GetInt32(0)
,PartID = reader.GetInt32(15)
,PartDesc = reader.GetString(1)
,PartNumber = reader.GetString(7)
,SupplierID = reader.GetString(16)
,AccountType = reader.GetString(3)
,CurrName = reader.GetString(4)
,PartQuantity = (double)reader.GetDecimal(5)
,PiecePrice = (double)reader.GetDecimal(6)
,Amount = (double)reader.GetDecimal(5) * (double)reader.GetDecimal(6)
});
}
}
}
return results;
}
}
I am using angularjs in this, so I am converting this data to JSON ..
Here is my controller :
public JsonResult GetList()
{
DateTime today = DateTime.Now;
List<NomsPRItem> model = CheckerConnection.LoadPRItems(new DateTime(today.Year, today.Month, 1, 0, 0, 0), today);
return Json(model, JsonRequestBehavior.AllowGet);
}
public JsonResult GetReportList(string from, string to)
{
DateTime fromd = DateTime.Now;
DateTime tod = DateTime.Now;
if (from != "undefined")
fromd = Convert.ToDateTime(from);
if (to != "undefined")
tod = Convert.ToDateTime(to);
fromd = new DateTime(fromd.Year, fromd.Month, fromd.Day, 0, 0, 0);
tod = new DateTime(tod.Year, tod.Month, tod.Day, 23, 59, 59);
return Json(CheckerConnection.LoadPRItems(fromd, tod), JsonRequestBehavior.AllowGet);
}
I hope someone can help me on this mistake !
Your requestID is long and you are converting it to Int32.Change it to Int64 like this.
RequestID = reader.GetInt64(0)
,PartID = reader.GetInt64(15)
Models:
public class Dog
{
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
public string Name { get; set; }
public DateTime? Birthdate { get; set; }
public string Color { get; set; }
public string Race { get; set; }
public string ChipNumber { get; set; }
public byte[] Photo { get; set; }
public virtual ICollection<Record> Records { get; set; }
public virtual User User { get; set; }
}
public class Record
{
public Record()
{
Quota = 1;
}
[Key, DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public DateTime? Time { get; set; }
[Required]
public string Name { get; set; }
public string Supplier { get; set; }
public double? Price { get; set; }
public int Quota { get; set; }
public string Note { get; set; }
public virtual Dog Dog { get; set; }
public virtual User User { get; set; }
}
WebapiConfig.cs:
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
in webapi calling to 'api/dogs' throws exception:
{"$id":"1","Message":"An error has occurred.","ExceptionMessage":"The
'ObjectContent1' type failed to serialize the response body for
content type 'application/json;
charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"$id":"2","Message":"An
error has occurred.","ExceptionMessage":"Error getting value from
'Records' on
'System.Data.Entity.DynamicProxies.Dog_2EE5CBDAE5320B6E973C971E716C24610E64BF4CECE05B6719C5876F271BA911'.","ExceptionType":"Newtonsoft.Json.JsonSerializationException","StackTrace":"
at Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object
target)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter
writer, Object value, JsonContainerContract contract, JsonProperty
member, JsonProperty property, JsonContract& memberContract, Object&
memberValue)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter
writer, Object value, JsonObjectContract contract, JsonProperty
member, JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter
writer, IEnumerable values, JsonArrayContract contract, JsonProperty
member, JsonContainerContract collectionContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter
writer, Object value, JsonContract valueContract, JsonProperty member,
JsonContainerContract containerContract, JsonProperty
containerProperty)\r\n at
Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter
jsonWriter, Object value, Type objectType)\r\n at
Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter
jsonWriter, Object value, Type objectType)\r\n at
Newtonsoft.Json.JsonSerializer.Serialize(JsonWriter jsonWriter, Object
value)\r\n at
System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type
type, Object value, Stream writeStream, Encoding
effectiveEncoding)\r\n at
System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type
type, Object value, Stream writeStream, Encoding
effectiveEncoding)\r\n at
System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type
type, Object value, Stream writeStream, HttpContent content)\r\n at
System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type
type, Object value, Stream writeStream, HttpContent content,
TransportContext transportContext, CancellationToken
cancellationToken)\r\n--- End of stack trace from previous location
where exception was thrown ---\r\n at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)\r\n at
System.Runtime.CompilerServices.TaskAwaiter.GetResult()\r\n at
System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()","InnerException":{"$id":"3","Message":"An
error has occurred.","ExceptionMessage":"An error occurred while
executing the command definition. See the inner exception for
details.","ExceptionType":"System.Data.Entity.Core.EntityCommandExecutionException","StackTrace":"
at
System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior)\r\n at
System.Data.Entity.Core.Objects.Internal.ObjectQueryExecutionPlan.Execute[TResultType](ObjectContext
context, ObjectParameterCollection parameterValues)\r\n at
System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.b__6()\r\n
at
System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func1
func, IDbExecutionStrategy executionStrategy, Boolean
startLocalTransaction, Boolean releaseConnectionOnSuccess)\r\n at
System.Data.Entity.Core.Objects.ObjectQuery1.<>c__DisplayClass7.b__5()\r\n
at
System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1
operation)\r\n at
System.Data.Entity.Core.Objects.ObjectQuery1.GetResults(Nullable1
forMergeOption)\r\n at
System.Data.Entity.Core.Objects.ObjectQuery1.Execute(MergeOption
mergeOption)\r\n at
System.Data.Entity.Core.Objects.DataClasses.EntityCollection1.Load(List1
collection, MergeOption mergeOption)\r\n at
System.Data.Entity.Core.Objects.DataClasses.EntityCollection1.Load(MergeOption
mergeOption)\r\n at
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.Load()\r\n at
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.DeferredLoad()\r\n
at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.LoadProperty[TItem](TItem
propertyValue, String relationshipName, String targetRoleName, Boolean
mustBeNull, Object wrapperObject)\r\n at
System.Data.Entity.Core.Objects.Internal.LazyLoadBehavior.<>c__DisplayClass72.b__1(TProxy
proxy, TItem item)\r\n at
System.Data.Entity.DynamicProxies.Dog_2EE5CBDAE5320B6E973C971E716C24610E64BF4CECE05B6719C5876F271BA911.get_Records()\r\n
at GetRecords(Object )\r\n at
Newtonsoft.Json.Serialization.DynamicValueProvider.GetValue(Object
target)","InnerException":{"$id":"4","Message":"An error has
occurred.","ExceptionMessage":"There is already an open DataReader
associated with this Command which must be closed
first.","ExceptionType":"System.InvalidOperationException","StackTrace":"
at
System.Data.SqlClient.SqlInternalConnectionTds.ValidateConnectionForExecute(SqlCommand
command)\r\n at
System.Data.SqlClient.SqlConnection.ValidateConnectionForExecute(String
method, SqlCommand command)\r\n at
System.Data.SqlClient.SqlCommand.ValidateCommand(String method,
Boolean async)\r\n at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource1 completion, Int32 timeout, Task& task,
Boolean asyncWrite)\r\n at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method)\r\n at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method)\r\n at
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior)\r\n at
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior
behavior)\r\n at
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand
t, DbCommandInterceptionContext1 c)\r\n at
System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget
target, Func3 operation, TInterceptionContext interceptionContext,
Action3 executing, Action3 executed)\r\n at
System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand
command, DbCommandInterceptionContext interceptionContext)\r\n at
System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior
behavior)\r\n at
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior
behavior)\r\n at
System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior)"}}}}
solved.
created DTO of DOG and insted of returning a USER and RECORDS inside the DOGDTO it now return UserId and list of RecordIds
I have the following scenario in my database. It is a record of Studies and those studies have other studies as prerequisites. In my DB design, it looks like this:
And my code looks something like this:
public class Study
{
public int ID { get; set; }
public string Topic { get; set; }
public byte TypeID { get; set; }
public virtual StudyType Type { get; set; }
public bool Deprecated { get; set; }
public virtual ICollection<Study> Prerequisites { get; set; }
}
public class StudyType
{
public byte ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Study> Studies { get; set; }
}
public class MyContext : DbContext
{
public DbSet<Study> Studies { get; set; }
public DbSet<StudyType> StudyTypes { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Study>()
.HasMany(p=>p.Prerequisites)
.WithMany().Map(ps =>
{
ps.ToTable("Prerequisites");
ps.MapLeftKey(x=>x.ID,"StudyID");
ps.MapRightKey(y=>y.ID,"PrerequisiteID");
});
}
I'm not super good at the EF syntax, but from what I've found Googling, that seems like it should work. Instead, I get Sequence contains more than one matching element.
I found this, but since the entity is referencing itself, I can't exactly rename the key field in only one of the tables: http://social.msdn.microsoft.com/Forums/eu/adonetefx/thread/745a2c4f-cb66-41ad-9524-15aa198c40c7
Anybody help me through this?
EDIT
Here is the full stack trace of the exception:
It executes on a line of LINQ: var x = from s in db.Studies select s;
Server stack trace:
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.ManyToManyAssociationMappingConfiguration`2.Configure(DbAssociationSetMapping associationSetMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(DbEntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel)
at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel()
at System.Lazy`1.CreateValue()
Exception rethrown at [0]:
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.ManyToManyAssociationMappingConfiguration`2.Configure(DbAssociationSetMapping associationSetMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Navigation.NavigationPropertyConfiguration.Configure(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Utilities.IEnumerableExtensions.Each[T](IEnumerable`1 ts, Action`1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigureAssociationMappings(DbDatabaseMapping databaseMapping)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(DbEntityTypeMapping entityTypeMapping, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel)
at System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_Provider()
at System.Linq.Queryable.Select[TSource,TResult](IQueryable`1 source, Expression`1 selector)
at DataAccess.Sql.SqlStudyRepository.GetAll() in C:\Side Work\Rephidim Church\Tuchikos 2011\Program\DataAccess\Sql\SqlStudyRepository.cs:line 22
at API.Controllers.StudiesController.Index() in C:\Side Work\Rephidim Church\Tuchikos 2011\Program\API\Controllers\StudiesController.cs:line 24
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
This is what I have in an EntityTypeConfiguration<> implementation for a similar situation in CTP5.
HasMany(g => g.SubGroups)
.WithMany(g => g.ParentGroups)
.Map(m => m.ToTable("Groups_SubGroups"));
Not sure exactly how that translates to configuring the DbContext directly, but I imagine it should be close.
If memory serves, LeftKey() RightKey() syntax wasn't quite there in CTP5, so you just have to use the default column names that it creates or is expecting. In my case, it is GroupId and GroupId1. That follows the pattern <class>Id and <class>Id1, not <field> and <field>1 by the way.
The error that you're getting does seem familiar and I don't remember that the solution was obvious in any way. But, I did set this all up a while ago so the memories of how I arrived at something that works is a bit swiss cheesed. Hope it helps some.