EntityFramework: How do I issue an auto-increment ID other than `SaveChanges()`?

Asked 2 years ago, Updated 2 years ago, 78 views

Data from self-made SRPG games are stored in the database under the Entity Framework Code-First.The tables include Character, Item, Weapon, Equipment, and so on.

I was able to implement it normally, but I can't solve one thing.

It means that the auto-increment ID is not issued until you call SaveChanges() and remains 0. For SRPG, read/write/insert/delete all .Local cache only during the game because it does not save in the middle.Then, even if you insert the item you got halfway into the database, it will remain ID=0 and you will not be able to use it (until you save it) from the program that expects a unique item ID.If you can't delete it as it is, it's the most troubling thing.

I'm sure everyone has trouble using the Entity Framework for games, but what solution can you come up with?

c# .net entity-framework

2022-09-30 11:54

1 Answers

I think it's better to use Interlocked or Guid instead of Identity.
If you have more than one client, you might want to set the key to 64 bits, DB number the top 32 bits per boot, and use Interlocked for the bottom 32 bits.

A method used in DataSet and so on is to assign a temporary Id before saving.In this case, use DatabaseGenerated(DatabaseGeneratedOption.Identity) with Interlocked to

public class Hoge
{
    [Key]
    DatabaseGenerated(DatabaseGeneratedOption.Identity)
    public int Id {get;set;}

    private static int_TempId;

    public static Hoge NewHoge()
    {
        return new Hoge()
        {
            // A temporary Id is numbered sequentially from -1.
            Id = Interlocked.Decrement(ref_TempId)
        };
    }
}

Define the entity as shown in , and call it NewXXX when you create a new record.

In any case, be aware that foreign key items will not be reflected unless explicitly implemented.


2022-09-30 11:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.