我已经阅读了几个 关于此的问题 ,但我尝试了他们的解决方案(每个问题基本相同)但没有成功。
我创建了一个模型并用它来更新本地数据库 (.sdf) 文件。现在,我正在尝试添加一个实体,但它失败了。这意味着它甚至不会保存任何实体。我已经identity
为我的 PK 设置了字段,配置了StoredGeneratedPattern
属性,查看了直接在 XML 中手动设置它(它就在那里)。我仍然无法保存任何东西。我错过了什么?
实体关系模型
模型 XML 配置 (TestDbEntities.edmx)
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="2.0" xmlns:edmx="http://schemas.microsoft.com/ado/2008/10/edmx">
<!-- EF Runtime content -->
<edmx:Runtime>
<!-- SSDL content -->
<edmx:StorageModels>
<Schema Namespace="TestDbModel.Store" Alias="Self" Provider="System.Data.SqlServerCe.3.5" ProviderManifestToken="3.5" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/02/edm/ssdl">
<EntityContainer Name="TestDbModelStoreContainer">
<EntitySet Name="UserMessages" EntityType="TestDbModel.Store.UserMessages" store:Type="Tables" Schema="dbo" />
<EntitySet Name="Users" EntityType="TestDbModel.Store.Users" store:Type="Tables" Schema="dbo" />
<AssociationSet Name="Rel_User_Message" Association="TestDbModel.Store.Rel_User_Message">
<End Role="users" EntitySet="Users" />
<End Role="messages" EntitySet="UserMessages" />
</AssociationSet>
</EntityContainer>
<EntityType Name="UserMessages">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Name="ID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="Message" Type="nvarchar" Nullable="true" MaxLength="1000" />
<Property Name="Author_ID" Type="int" Nullable="false" />
</EntityType>
<EntityType Name="Users">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Name="ID" Type="int" StoreGeneratedPattern="Identity" Nullable="false" />
<Property Name="Identity" Type="nvarchar" Nullable="false" MaxLength="100" />
<Property Name="Password" Type="nvarchar" Nullable="false" MaxLength="100" />
<Property Name="Name" Type="nvarchar" Nullable="false" MaxLength="100" />
<Property Name="LastName" Type="nvarchar" Nullable="false" MaxLength="100" />
<Property Name="Active" Type="bit" Nullable="false" DefaultValue="false" />
</EntityType>
<Association Name="Rel_User_Message">
<End Role="users" Type="TestDbModel.Store.Users" Multiplicity="1" />
<End Role="messages" Type="TestDbModel.Store.UserMessages" Multiplicity="*" />
<ReferentialConstraint>
<Principal Role="users">
<PropertyRef Name="ID" />
</Principal>
<Dependent Role="messages">
<PropertyRef Name="Author_ID" />
</Dependent>
</ReferentialConstraint>
</Association>
</Schema></edmx:StorageModels>
<!-- CSDL content -->
<edmx:ConceptualModels>
<Schema Namespace="TestDbModel" Alias="Self" xmlns:annotation="http://schemas.microsoft.com/ado/2009/02/edm/annotation" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
<EntityContainer Name="TestDbEntities" annotation:LazyLoadingEnabled="true">
<EntitySet Name="UserMessages" EntityType="TestDbModel.UserMessage" />
<EntitySet Name="Users" EntityType="TestDbModel.User" />
<AssociationSet Name="Rel_User_Message" Association="TestDbModel.Rel_User_Message">
<End Role="users" EntitySet="Users" />
<End Role="messages" EntitySet="UserMessages" />
</AssociationSet>
</EntityContainer>
<EntityType Name="UserMessage">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Type="Int32" Name="ID" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Type="String" Name="Message" MaxLength="1000" FixedLength="false" Unicode="true" />
<NavigationProperty Name="Author" Relationship="TestDbModel.Rel_User_Message" FromRole="messages" ToRole="users" />
</EntityType>
<EntityType Name="User">
<Key>
<PropertyRef Name="ID" />
</Key>
<Property Type="Int32" Name="ID" Nullable="false" annotation:StoreGeneratedPattern="Identity" />
<Property Type="String" Name="Identity" MaxLength="100" FixedLength="false" Unicode="true" Nullable="false" />
<Property Type="String" Name="Password" MaxLength="100" FixedLength="false" Unicode="true" Nullable="false" />
<Property Type="String" Name="Name" MaxLength="100" FixedLength="false" Unicode="true" Nullable="false" />
<Property Type="String" Name="LastName" MaxLength="100" FixedLength="false" Unicode="true" Nullable="false" />
<Property Type="Boolean" Name="Active" Nullable="false" DefaultValue="False" />
<NavigationProperty Name="AuthoredMessages" Relationship="TestDbModel.Rel_User_Message" FromRole="users" ToRole="messages" />
</EntityType>
<Association Name="Rel_User_Message">
<End Type="TestDbModel.User" Role="users" Multiplicity="1" />
<End Type="TestDbModel.UserMessage" Role="messages" Multiplicity="*" />
</Association>
</Schema>
</edmx:ConceptualModels>
<!-- C-S mapping content -->
<edmx:Mappings>
<Mapping Space="C-S" xmlns="http://schemas.microsoft.com/ado/2008/09/mapping/cs">
<EntityContainerMapping StorageEntityContainer="TestDbModelStoreContainer" CdmEntityContainer="TestDbEntities">
<EntitySetMapping Name="UserMessages">
<EntityTypeMapping TypeName="IsTypeOf(TestDbModel.UserMessage)">
<MappingFragment StoreEntitySet="UserMessages">
<ScalarProperty Name="ID" ColumnName="ID" />
<ScalarProperty Name="Message" ColumnName="Message" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<EntitySetMapping Name="Users">
<EntityTypeMapping TypeName="IsTypeOf(TestDbModel.User)">
<MappingFragment StoreEntitySet="Users">
<ScalarProperty Name="ID" ColumnName="ID" />
<ScalarProperty Name="Identity" ColumnName="Identity" />
<ScalarProperty Name="Password" ColumnName="Password" />
<ScalarProperty Name="Name" ColumnName="Name" />
<ScalarProperty Name="LastName" ColumnName="LastName" />
<ScalarProperty Name="Active" ColumnName="Active" />
</MappingFragment>
</EntityTypeMapping>
</EntitySetMapping>
<AssociationSetMapping Name="Rel_User_Message" TypeName="TestDbModel.Rel_User_Message" StoreEntitySet="UserMessages">
<EndProperty Name="users">
<ScalarProperty Name="ID" ColumnName="Author_ID" />
</EndProperty>
<EndProperty Name="messages">
<ScalarProperty Name="ID" ColumnName="ID" />
</EndProperty>
</AssociationSetMapping>
</EntityContainerMapping>
</Mapping></edmx:Mappings>
</edmx:Runtime>
<!-- EF Designer content (DO NOT EDIT MANUALLY BELOW HERE) -->
<Designer xmlns="http://schemas.microsoft.com/ado/2008/10/edmx">
<Connection>
<DesignerInfoPropertySet>
<DesignerProperty Name="MetadataArtifactProcessing" Value="EmbedInOutputAssembly" />
</DesignerInfoPropertySet>
</Connection>
<Options>
<DesignerInfoPropertySet>
<DesignerProperty Name="ValidateOnBuild" Value="true" />
<DesignerProperty Name="EnablePluralization" Value="False" />
<DesignerProperty Name="IncludeForeignKeysInModel" Value="False" />
</DesignerInfoPropertySet>
</Options>
<!-- Diagram content (shape and connector positions) -->
<Diagrams>
<Diagram Name="Model1">
<EntityTypeShape EntityType="TestDbModel.UserMessage" Width="1.5" PointX="2.625" PointY="0.5" Height="1.5956835937499996" />
<EntityTypeShape EntityType="TestDbModel.User" Width="1.5" PointX="0.5" PointY="0.5" Height="2.3648893229166665" />
<AssociationConnector Association="TestDbModel.Rel_User_Message" >
<ConnectorPoint PointX="2" PointY="1.2978417968749998" />
<ConnectorPoint PointX="2.625" PointY="1.2978417968749998" />
</AssociationConnector>
</Diagram>
</Diagrams>
</Designer>
</edmx:Edmx>
C#(示例代码)
User user = new User()
{
Identity = name + "." + lastName, // generated value
Password = Convert.ToBase64String(password), // generated value
Name = name, // ...
LastName = lastName, // ...
Active = rand.NextDouble() > 0.7 // 70% de chance d'être actif
};
ctx.AddToUsers(user);
try
{
ctx.SaveChanges();
Console.WriteLine("Created user #" + (i + 1) + " : " + user.Identity);
}
catch (Exception e)
{
Console.WriteLine(e.InnerException);
Console.WriteLine("Collision for name " + user.Identity);
}
堆栈跟踪错误
L'exception System.Data.UpdateException n'a pas été gérée
Message=Une erreur s'est produite lors de la mise à jour des entrées. Pour plus d'informations, consultez l'exception interne.
Source=System.Data.Entity
StackTrace:
à System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
à System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
à System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
à System.Data.Objects.ObjectContext.SaveChanges()
à TestApplication.entity.EntitiesTest.CreateTestDbEntities(TestDbEntities ctx) dans C:\Users\yrochon\Documents\Visual Studio 2010\Projects\TestApplication\TestApplication\entity\Entities.cs:ligne 119
à TestApplication.entity.EntitiesTest.Test() dans C:\Users\yrochon\Documents\Visual Studio 2010\Projects\TestApplication\TestApplication\entity\Entities.cs:ligne 26
à TestApplication.Program.Main(String[] args) dans C:\Users\yrochon\Documents\Visual Studio 2010\Projects\TestApplication\TestApplication\Program.cs:ligne 18
à System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()
InnerException: System.Data.EntityCommandCompilationException
Message=Une erreur s'est produite lors de la préparation de la définition de la commande. Pour plus de détails, consultez l'exception interne.
Source=System.Data.Entity
StackTrace:
à System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
à System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues)
à System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
à System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
InnerException: System.NotSupportedException
Message=Les clés et les valeurs générées par le serveur ne sont pas prises en charge par SQL Server Compact.
Source=System.Data.SqlServerCe.Entity
StackTrace:
à System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateReturningSql(StringBuilder commandText, DbModificationCommandTree tree, ExpressionTranslator translator, DbExpression returning)
à System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateInsertSql(DbInsertCommandTree tree, List`1& parameters, Boolean isLocalProvider)
à System.Data.SqlServerCe.SqlGen.SqlGenerator.GenerateSql(DbCommandTree tree, List`1& parameters, CommandType& commandType, Boolean isLocalProvider)
à System.Data.SqlServerCe.SqlCeProviderServices.CreateCommand(DbProviderManifest providerManifest, DbCommandTree commandTree)
à System.Data.SqlServerCe.SqlCeProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
à System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree)
à System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree)
à System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
InnerException:
这是唯一的解决方案吗?手动生成身份(即使它们应该由数据库自动递增)?