0

Hi I create C# windows form project and use "Microsoft® SQL Server® Compact 4.0 SP1" as database. I create my project with entity framework and code first approach. but I get some error. I want use GUID as type of primary key for tables and my code is:

   [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid id { get; set; }

but I get this error:

InvalidOperationException: Server-generated keys are only supported for identity columns. The column 'id' has type 'SqlServerCe.uniqueidentifier', which is not a valid type for an identity column.

and when remove [DatabaseGenerated] and [key] I get duplicate error. I searching and find SQL Compact in entity framework only knows int and big int as primary key and auto increment it, but I am not sure. how can i fix this and use GUID and primary key? pleases help.

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
sadegh
  • 103
  • 5
  • 1
    You can't. You need to either use a different database that supports auto-generated GUIDs or use a different data type. Microsoft stopped development of SQL Server CE in favour of recommending SQLite for file-based databases, so that would be the first place to look. I'm not sure whether it supports auto-generated GUIDs or not. – jmcilhinney Jun 16 '23 at 06:23
  • Please apply relevant tags and only relevant tags. Regardless of your application, this question has nothing to do with SQL or WinForms. – jmcilhinney Jun 16 '23 at 06:25
  • https://stackoverflow.com/questions/23081096/entity-framework-6-guid-as-primary-key-cannot-insert-the-value-null-into-column Question is answered here. The trick is to modify the OnCreate bit in the migration file. – Morten Bork Jun 16 '23 at 06:36
  • Remove the Identity attribute and assign a unique guid in code – ErikEJ Jun 16 '23 at 06:48
  • @jmcilhinney Thank you. I finally try and learn how to use SQLite. almost all my of problem solved. – sadegh Jun 17 '23 at 18:47

0 Answers0