2012-10-01 76 views
0

我已經閱讀severalquestionson this已經有了,但我已經嘗試過他們的解決方案(基本上與每個問題相同),但沒有成功。帶自動增量列的實體框架

我已經創建了一個模型,並用它來更新本地數據庫(.sdf)文件。現在,我試圖添加一個實體,但它失敗了。這意味着它甚至不會拯救任何實體。我已經爲我的PK設置了identity字段,配置了StoredGeneratedPattern屬性,然後直接在XML中查看手動設置它(它在那裏)。我仍然無法保存任何東西。我錯過了什麼?

的實體關係模型

enter image description here

該模型的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: 

this the only solution?手動生成身份(即使它們應該由數據庫自動增加)?

+0

你得到了什麼錯誤? –

+0

是數據庫第一或模型的第一種方法? –

+0

我更新了問題。對不起,VS安裝在法國,這就是它。基本上,它不能保存實體,因爲它的身份字段被設置爲'0'。 –

回答

1

將SQL精簡版升級到Version 4並自動遞增該ID。

+0

我安裝了3.5版本。試圖升級.... –

+1

我不得不在這裏安裝VS 2010 SP1(http://www.microsoft.com/en-us/download/details.aspx?id=23691)和一些「神祕工具」: http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/8c46681f-5a64-4eeb-8c2b-ae9bf29057bd(去微軟的路!)但現在它工作。 –