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.
Related
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();
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 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.
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.
I am using code-first POCOs with EF4, CTP5. I've got a table with a lot of columns in it (over 100). I want to split the table into multiple types (aka "Table Splitting") so that I don't have to fetch all the data every time I want some basic information.
I can't seem to find any documentation on this using Google. I've found references to the concept, "Table Splitting", and I've also seen how to do it using an EDMX file, but no samples for code-first.
I was hoping it would be as simple as defining another entity type and relating them as you would any other navigation property like so...
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
[ForeignKey("UserID")]
public virtual UserDetails Details { get; set; }
}
public class UserDetails
{
public int UserID { get; set; }
public string MoreData { get; set; }
[ForeignKey("UserID")]
public virtual User User { get; set; } // nice to have, but not required
}
And I call it like this...
return (from u in Context.Users // <-- error occurs here
where u.UserID == userID
select u).FirstOrDefault();
Unfortunately this does not seem to be working. I am getting the following error when I do this...
[IndexOutOfRangeException: Index was outside the bounds of the array.]
System.Data.Entity.ModelConfiguration.Conventions.Edm.PropertyMaxLengthConvention.System.Data.Entity.ModelConfiguration.Conventions.Edm.IEdmConvention<System.Data.Edm.EdmAssociationType>.Apply(EdmAssociationType associationType, EdmModel model) +598
System.Data.Entity.ModelConfiguration.Configuration.EdmConventionDispatcher.Dispatch(TEdmDataModelItem item) +100
System.Data.Entity.ModelConfiguration.Configuration.EdmConventionDispatcher.VisitEdmAssociationType(EdmAssociationType item) +22
System.Data.Entity.ModelConfiguration.Edm.Services.DataModelItemVisitor.VisitCollection(IEnumerable`1 collection, Action`1 visitMethod) +267
System.Data.Entity.ModelConfiguration.Edm.Services.EdmModelVisitor.VisitAssociationTypes(EdmNamespace edmNamespace, IEnumerable`1 associationTypes) +75
System.Data.Entity.ModelConfiguration.Edm.Services.EdmModelVisitor.VisitEdmNamespace(EdmNamespace item) +91
System.Data.Entity.ModelConfiguration.Configuration.EdmConventionDispatcher.VisitEdmNamespace(EdmNamespace item) +32
System.Data.Entity.ModelConfiguration.Edm.Services.DataModelItemVisitor.VisitCollection(IEnumerable`1 collection, Action`1 visitMethod) +267
System.Data.Entity.ModelConfiguration.Edm.Services.EdmModelVisitor.VisitNamespaces(EdmModel model, IEnumerable`1 namespaces) +75
System.Data.Entity.ModelConfiguration.Edm.Services.EdmModelVisitor.VisitEdmModel(EdmModel item) +47
System.Data.Entity.ModelConfiguration.Configuration.EdmConventionDispatcher.VisitEdmModel(EdmModel item) +45
System.Data.Entity.ModelConfiguration.Configuration.ConventionsConfiguration.ApplyModel(EdmModel model) +254
System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo, Boolean validateModel) +257
System.Data.Entity.ModelConfiguration.ModelBuilder.Build(DbConnection providerConnection) +172
System.Data.Entity.Internal.LazyInternalContext.CreateModel() +62
System.Lazy`1.CreateValue() +361
System.Lazy`1.LazyInitValue() +104
System.Lazy`1.get_Value() +89
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +358
System.Data.Entity.Internal.InternalContext.Initialize() +16
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +16
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +61
System.Data.Entity.Internal.Linq.InternalSet`1.get_Provider() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +13
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
TourFactory.Web.AgentWebsite.Models.Websites.WebsiteRepository.GetUser(Int32 userID) in C:\Code\hdtf\TF4\Web\AgentWebsite\Models\Websites\WebsiteRepository.cs:28
TourFactory.Web.AgentWebsite.Controllers.WebsiteController.get_Agent() in C:\Code\hdtf\TF4\Web\AgentWebsite\Controllers\WebsiteController.cs:42
TourFactory.Web.AgentWebsite.Controllers.WebsiteController.OnActionExecuting(ActionExecutingContext filterContext) in C:\Code\hdtf\TF4\Web\AgentWebsite\Controllers\WebsiteController.cs:55
System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +81
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +61
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +305
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830
System.Web.Mvc.Controller.ExecuteCore() +136
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +232
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +68
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +61
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +31
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +56
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +110
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
Removing the User.Details property makes the error go away, but then I can't use the nifty navigation features of EF4.
Using Complex Types is the only way you can map a table to multiple types. However, Code First (and EF in general) does NOT support lazy/Deferred loading for complex types. In other words, EF will always populate the complex type each time you read the entity from the database:
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public UserDetails Details { get; set; }
}
[ComplexType]
public class UserDetails
{
public string MoreData { get; set; }
}
The only way you can achieve lazy loading for your big table is by really splitting it into multiple tables and then you can use one-to-one associations to map it back to multiple entities.
For more info regarding Complex Types in EF Code First CTP, take a look at this article:
Associations in EF Code First CTP5: Part 1 – Complex Types
I know this question is more than a year but EF Code First supports table splitting and lazy loading at the same time.
Your model should be like this:
[Table("UserTable")]
public class User
{
[Key, ForeignKey("Details")]
public int UserID { get; set; }
public string UserName { get; set; }
public virtual UserDetails Details { get; set; }
}
[Table("UserTable")]
public class UserDetails
{
[Key, ForeignKey("User")]
public int UserID { get; set; }
public string MoreData { get; set; }
public virtual User User { get; set; }
}
Lazy loading (and eager loading) should work as expected.
Its important to note that table splitting works if
Entities have 1-to-1 relationship, and
Entities share the same Key
I guess the answer suggested by Rino is a better one. Though in the end you achieve same thing. But in the case of second one it's meant to do the exact same thing. First one can have problem when you cannot have apply [ComplexType] due to 3rd party code or you have a list of that type.
Use the second one or as in Fluent APIs as from Julia Lerman's book (splitting "People" table into "Person" and "PersonPhoto" entities.
modelBuilder.Entity<Person>().ToTable("People");
modelBuilder.Entity<PersonPhoto>().ToTable("People");