{"Server-generated keys and server-generated values are not supported by SQL Server Compact."}
I’m creating a small application for my friends and I decided to use SQL CE and Entity Framework. I’ve configured the database to use identities for primary keys in tables and I got an exception when I’ve tried to add a record.
According to information from internet Entity Framework doesn’t support database generated values. It is not a good news for me and I hope it will be fixed in next version of the framework.
I’ve decided to use a partial class of the Entity class and extend it with additional methods that will allow me to generate record id. I also moved from bigint ids to ids of type uniqueidentifier. Every Entity generated by the designer contains a static method that allows us to create an entity. I have an entity Author and generated create method for it is
1: public partial class Author : global::System.Data.Objects.DataClasses.EntityObject
2: {
3: /// <summary>
4: /// Create a new Author object.
5: /// </summary>
6: /// <param name="firstName">Initial value of FirstName.</param>
7: /// <param name="lastName">Initial value of LastName.</param>
8: /// <param name="id">Initial value of Id.</param>
9: public static Author CreateAuthor(string firstName, string lastName, global::System.Guid id)
10: {
11: Author author = new Author();
12: author.FirstName = firstName;
13: author.LastName = lastName;
14: author.Id = id;
15: return author;
16: }
17: …
18: }
My partial class for Author is like that one below.
1: public partial class Author
2: {
3: public static Author CreateAuthor(string firstName, string lastName)
4: {
5: Author author = new Author();
6: author.FirstName = firstName;
7: author.LastName = lastName;
8: author.Id = Guid.NewGuid();
9: return author;
10: }
11:
12: public static Author CreateAuthor()
13: {
14: Author author = new Author();
15: author.Id = Guid.NewGuid();
16: return author;
17: }
18: }
Than I can use this methods like Author newAuthor = Author.CreateAuthor();
The real downside of this technique is that if you have a database with a lot of entities you should create for all of them. In my case it works fine. Application database contains just several tables.
Leave a Reply