Server-generated keys and server-generated values are not supported by SQL Server Compact

女生的网名这么多〃 提交于 2019-11-27 19:38:38

When I hit this limitation, I changed the type to uniqueidentifier

Use uniqueidentifier or generate a bigint/int key value manually is your best option.

Something like this perhaps ...

    private static object lockObject = new object();

    private static long nextID = -1;

    public static long GetNextID()
    {
        lock (lockObject)
        {
            if (nextID == -1) nextID = DateTime.UtcNow.Ticks; else nextID++;
            return nextID;
        }
    }

This assumes that you don't generate more than one record per tick during an application run (plus the time to stop and restart). This is a reasonable assumption I believe, but if you want a totally bullet proof (but more complex) solution, go read the highest ID from the database and increment from that.

SQL CE version 4.0 fixed this problem with its Entity Framework provider.

I just hit this issue too... mostlytech's answer is probably the best option, GUIDs are very easy to use and the risk of key collision is very low (although not inexistant).

  • Why would you mark key as server-generated if it is not supported and will throw an exception? It's hard to make sence from the quoted paragraph.

Because SQL Server (not Compact) supports it, and other third parties may support it too... Entity Framework is not only for SQL Server Compact ;)

In my case, all of my classes have the primary key named "ID"

I created an interface

public class IID
{
    public Int32 ID { get; set; }
}

Then I create an extension method

public static Int32 GetNextID<T>(this ObjectSet<T> objects)
    where T : class, IID
    {
        T entry = objects.OrderByDescending(u => u.ID).FirstOrDefault();
        if (entry == default(T))
            return 1;
        return entry.ID + 1;
    }

Then when I need a new ID, I just do this:

MyObject myobj = new MyObject();
myobj.ID = entities.MyTable.GetNextID();

the other option is to use SqlCeResultSet on the tables that have the identity column.

i have a primary key named ID with data type of INT32 and have Identity Column

Just do this

MyEntity Entity = new MyEntity();

String Command;

command = "Insert into Message(Created,Message,MsgType)values('12/1/2014','Hello World',5); Entity.ExecuteStoreCommand(command);

--Exclude the primary key in the insert Statement

--Since the SQLCE do not support system generated keys

--Do not use LINQ because it supplies a default value to 0 for Primary keys that has a data type of INT

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