【发布时间】:2012-02-07 09:06:18
【问题描述】:
我正在使用 Entity Framework 向数据库表中插入一个新行,但我的问题是 ValidFromDate 列导致异常
“ValidFromDate”属性是对象关键信息的一部分 并且不能修改日期
我们的 DBA 已经定义了数据库,下图是 EDMX 文件的快照。 ValidFromDate 是 日期时间 列。
FarmAnimal 的想法是跟踪某些动物的历史。因此AnimalId 和 ValidFromDate 导致该行是唯一的。
现在的问题是,我怎样才能在具有这种模式的表中插入新行?
使用实体框架插入
var farmAnimal = new FarmAnimal {
AnimalId = insert.AnimalId,
ValidFromDate = insert.ValidFromDate // exception comes from this line,
etc.
};
entities.FarmAnimals.Add(farmAnimal);
更新:StackTrace
at System.Data.Objects.EntityEntry.DetectChangesInProperties(Boolean detectOnlyComplexProperties)
at System.Data.Objects.ObjectStateManager.DetectChangesInScalarAndComplexProperties(IList`1 entries)
at System.Data.Objects.ObjectStateManager.DetectChanges()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at xxx.Repositories.PairingRepository.UpdateFarmAnimals(IEnumerable`1 updates, IEnumerable`1 inserts) in xxx
at xxx.Services.PairingService.RemovePairingAnimals(List`1 animalIds) in xxx
at xxx.Controllers.PairingController.RemovePairingAnimals(List`1 animalIds) in xxx
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)
更新 2:实体框架文件
我添加了三个文件实体框架映射文件/生成器 EDMX 文件 ADO.NET DbContext 生成器 ADO.NET EntityObject 生成器(POCO)
【问题讨论】:
-
什么时候出现异常?保存更改时的设置器之一,ObjectSet.Add 方法?你能发布堆栈跟踪吗?
-
@cynic 查看源代码块的注释。我现在将获取堆栈跟踪。感谢您的宝贵时间。
-
我看到您正在使用 DbSet/DbContext 包装层。实体是 POCO,还是使用所有更改跟踪逻辑生成的?
-
另外,当内存上下文 (FarmAnimals.Local) 中至少存在一个 FarmAnimal 时,我认为调用失败?
-
@cynic 我假设我的 .tt 文件不是“ADO.NET 自跟踪实体生成器”,因为生成的 .cs 文件似乎只包含 POCO。
标签: c# entity-framework entity-framework-4.1