gpt4 book ai didi

c# - 为什么我在使用 EF 5 向 Oracle 11gR2 数据库添加订单时得到 `InvalidOperationException`?

转载 作者:行者123 更新时间:2023-11-30 22:10:07 24 4
gpt4 key购买 nike

为什么我在使用 EF 5 向 Oracle 11gR2 数据库添加订单时收到 InvalidOperationException

我正在使用来自 Sears.com 的订单提要,并使用 VS 2013 Professional 中的 Entity Framework 5 将订单数据添加到 Oracle 数据库中。直到订单号 835 为止,一切都按预期工作,此时它抛出异常。

调用 SaveChanges() 会抛出 InvalidOperationExceptionInvalidOperationException 仅应在已根据 dbContext 类处理上下文时抛出:

//
// Summary:
// Saves all changes made in this context to the underlying database.
//
// Returns:
// The number of objects written to the underlying database.
//
// Exceptions:
// System.InvalidOperationException:
// Thrown if the context has been disposed.
public virtual int SaveChanges();

我的代码设置如下:

using (Entities rds = new Entities())
{
foreach (poresponsePurchaseorder po in newSears.purchaseorder)
{
var searsOrders = new SEARS_COM_ORDERS();
searsOrders.ORDER_CONFIRMATION_NUMBER = po.customerorderconfirmationnumber.ToString() ?? "missing data";
searsOrders.CUSTOMER_EMAIL = po.customeremail ?? "missing data";
...
rds.SEARS_COM_ORDERS.Add(searsOrders);
foreach (poresponsePurchaseorderPoline poLine in po.poline)
{
var searsOrderItems = new SEARS_COM_ORDER_ITEMS();
searsOrderItems.PO_NUMBER = (int)po.ponumber;
searsOrderItems.LINE_NUMBER = (int)poLine.polineheader.linenumber;
...
rds.SEARS_COM_ORDER_ITEMS.Add(searsOrderItems);
}
...
try
{
int y = rds.SaveChanges();
Console.WriteLine(y + " Records added");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
Console.ReadKey();
}
}
}

Entities 的调用不会在其他任何地方进行,Dispose(); 也不会在任何时候调用(除了 终止期间的隐式调用>使用语句)

异常(exception)是:

System.InvalidOperationException: The changes to the database were committed successfully, but an error occurred while updating the object context. Th
e ObjectContext might be in an inconsistent state. Inner exception message: AcceptChanges cannot continue because the object's key values conflict wit
h another object in the ObjectStateManager. Make sure that the key values are unique before calling AcceptChanges.
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at MarketplaceIntegrator.Utilities.Marketplaces.SearsCom.SearsTests.GetSearsOrders(String from, String to) in c:\Users\roberth\Programming_Projects
\VisualStudio\vsOnline\MarketplaceIntegrator\Utilities\Marketplaces\SearsCom\SearsTests.cs:line 201

有什么想法吗?

--编辑--

我的数据库模型似乎引用了数据库初始开发期间使用的旧主键,从数据库更新模型导致将一组奇怪的混合主键添加到模型本身。

我的订单商品表和订单表中唯一的主键应该是 ID,它通过序列自动递增。除了订单项表上的 ID 和订单表中的 PO_NUMBER 和 ID 之外,模型还添加了 PO_NUMBER 和 LINE_NUMBER,如 edmx 所示:

 <EntityType Name="SEARS_COM_ORDER_ITEMS">
<Key>
<PropertyRef Name="ID" />
</Key>
<EntityType Name="SEARS_COM_ORDERS">
<Key>
<PropertyRef Name="ID" />
</Key>

但是在 SSDL 中它正确地列出了 key 。

enter image description here

更改后重新运行程序会导致以下错误。所以现在问题变成了**为什么 EDMX 显示的数据与底层 SSDL 不同并触发新错误? **

新异常:

System.Data.Entity.Infrastructure.DbUpdateException: Error retrieving values from ObjectStateEntry. See inner exception for details. ---> System.Data.
UpdateException: Error retrieving values from ObjectStateEntry. See inner exception for details. ---> System.Data.MappingException:
RDS.msl(80,10) : error 3002: Problem in mapping fragments starting at line 80:Potential runtime violation of table SEARS_COM_ORDER_ITEMS's keys (SEARS
_COM_ORDER_ITEMS.ID): Columns (SEARS_COM_ORDER_ITEMS.ID) are mapped to EntitySet SEARS_COM_ORDER_ITEMS's properties (SEARS_COM_ORDER_ITEMS.ID) on the
conceptual side but they do not form the EntitySet's key properties (SEARS_COM_ORDER_ITEMS.ID, SEARS_COM_ORDER_ITEMS.LINE_NUMBER, SEARS_COM_ORDER_ITEM
S.PO_NUMBER).

RDS.msl(97,10) : error 3002: Problem in mapping fragments starting at line 97:Potential runtime violation of table SEARS_COM_ORDERS's keys (SEARS_COM_
ORDERS.ID): Columns (SEARS_COM_ORDERS.ID) are mapped to EntitySet SEARS_COM_ORDERS's properties (SEARS_COM_ORDERS.ID) on the conceptual side but they
do not form the EntitySet's key properties (SEARS_COM_ORDERS.ID, SEARS_COM_ORDERS.PO_NUMBER).

at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGenerateViews(StorageEntityContainerMapping entityContainerMap, Dictio
nary`2 resultDictionary)
at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.SerializedGetGeneratedViews(EntityContainer container)
at System.Data.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.Mapping.StorageMappingItemCollection.ViewDictionary.GetGeneratedView(EntitySetBase extent, MetadataWorkspace workspace, StorageMappi
ngItemCollection storageMappingItemCollection)
at System.Data.Mapping.Update.Internal.ViewLoader.InitializeEntitySet(EntitySetBase entitySetBase, MetadataWorkspace workspace)
at System.Data.Mapping.Update.Internal.ViewLoader.SyncInitializeEntitySet[TArg,TResult](EntitySetBase entitySetBase, MetadataWorkspace workspace, F
unc`2 evaluate, TArg arg)
at System.Data.Mapping.Update.Internal.ViewLoader.SyncContains[T_Element](EntitySetBase entitySetBase, MetadataWorkspace workspace, Set`1 set, T_El
ement element)
at System.Data.Mapping.Update.Internal.ExtractorMetadata..ctor(EntitySetBase entitySetBase, StructuralType type, UpdateTranslator translator)
at System.Data.Mapping.Update.Internal.UpdateTranslator.GetExtractorMetadata(EntitySetBase entitySetBase, StructuralType type)
at System.Data.Mapping.Update.Internal.ExtractorMetadata.ExtractResultFromRecord(IEntityStateEntry stateEntry, Boolean isModified, IExtendedDataRec
ord record, Boolean useCurrentValues, UpdateTranslator translator, ModifiedPropertiesBehavior modifiedPropertiesBehavior)
at System.Data.Mapping.Update.Internal.RecordConverter.ConvertStateEntryToPropagatorResult(IEntityStateEntry stateEntry, Boolean useCurrentValues,
ModifiedPropertiesBehavior modifiedPropertiesBehavior)
--- End of inner exception stack trace ---
at System.Data.Mapping.Update.Internal.RecordConverter.ConvertStateEntryToPropagatorResult(IEntityStateEntry stateEntry, Boolean useCurrentValues,
ModifiedPropertiesBehavior modifiedPropertiesBehavior)
at System.Data.Mapping.Update.Internal.ExtractedStateEntry..ctor(UpdateTranslator translator, IEntityStateEntry stateEntry)
at System.Data.Mapping.Update.Internal.UpdateTranslator.LoadStateEntry(IEntityStateEntry stateEntry)
at System.Data.Mapping.Update.Internal.UpdateTranslator.PullModifiedEntriesFromStateManager()
at System.Data.Mapping.Update.Internal.UpdateTranslator.ProduceCommands()
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 MarketplaceIntegrator.Utilities.Marketplaces.SearsCom.SearsTests.GetSearsOrders(String from, String to) in c:\Users\roberth\Programming_Projects
\VisualStudio\vsOnline\MarketplaceIntegrator\Utilities\Marketplaces\SearsCom\SearsTests.cs:line 200

--编辑2--

进一步的研究似乎需要手动编辑 edmx:

根据 Microsoft :

The conceptual model will be updated only for objects that are added to the database. All other changes to the conceptual model must be made manually.

手动更改引用字段的属性以将实体键设置为 false,这让我再次回到原来的错误。

最佳答案

对此的实际修复包括多个项目。在我的例子中,以下原因导致了错误:

在生成模型后更改数据库中的主键。

如果发生这种情况,需要采取以下步骤来纠正此问题:

  • 从数据库更新模型
  • 通过删除旧引用(将属性上的 Entity Key 设置为 false 并将 StoreGeneratedPattern 更改为 来修复 edmx 上的主键>无)
  • 确保新 key 的 Entity Key 设置为 true 并且 StoreGeneratedPattern 设置为 Identity
  • 通过右键单击 edmx 并选择使用文本编辑器打开并根据需要进行编辑以显示正确的 key ,验证 SSDL 上的信息是否正确。特别是在错误的键上查找 StoreGeneratedPattern="Identity" 并将其移至正确的键(如果不存在)。 SSDL 应该镜像 EDMX 模型,更新之前的项目后出现错误可能意味着 SSDL 与模型不同

至少可以说,该异常具有误导性,因为 SaveChanges() 调用的文档表明它在 dbContext 关闭时被抛出,而错误消息表明当 < em>两个实际上都不是真的(反正就我而言)。

我知道这篇文章冗长,但希望它能帮助其他人解决同样的问题。

关于c# - 为什么我在使用 EF 5 向 Oracle 11gR2 数据库添加订单时得到 `InvalidOperationException`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21094176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com