UpdateException when using SQL Server Compact with Entity Framework

℡╲_俬逩灬. 提交于 2019-12-11 23:38:23

问题


I am trying to use Entity Framework with SQL Server Compact. I can perform reading such as :

var context = new TestEntities();

foreach (var p in context.Personnes)
{
    Console.WriteLine(p.prenom + " " + p.nom);
}

but I can't perform insert :

var context = new TestEntities();

context.Personnes.AddObject(new Personne() {nom = "Test", prenom = "Test" });

context.SaveChanges();

An UpdateException is raised when I try to do this. The Personne table has just 3 columns: id (int, primary key), nom (varchar) and prenom (varchar).

Here is the display I have when I run the program :

System.Data.EntityCommandCompilationException: 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. ---> System.NotSupportedException: Les clès et les valeurs générées par le serveur ne sont pas prises en charge par SQL Server Compact.

System.Data.SqlServerCe.SqlGen.DmlSqlGenerator.GenerateInsertSql(DbInsertCommandTree tree, List1& parameters, Boolean isLocalProvider) … System.Data.SqlServerCe.SqlGen.SqlGenerator.GenerateSql(DbCommandTree tree, List1& 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) --- Fin de la trace de la pile d'exception interne --- … System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree) … System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary2 identifierValues) … System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary2 identifierValues, List`1 generatedValues) … System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)

Thank you :)


回答1:


SqlServer Compact doesn't support server-side key generation. You must generate key on application side. So set id explicitly. Here is example.

context.Personnes.AddObject(new Personne() {id = lastId++, nom = "Test", prenom = "Test" });

You have to maintain lastId. Code that I wrote above will work only in single thread.



来源:https://stackoverflow.com/questions/4736177/updateexception-when-using-sql-server-compact-with-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!