简体   繁体   中英

Entity Framwork and holding IDs

I work with the Entity Framework and C# and have the following problem. I need to link objects in my program to an entity from the database. So if I have an object A and an entity BI stored the ID of B in A. And then I do stuff with A and eventually want to access B again. I did this like so:

using (var context = new TestModelContainer()) {
    var B = context.BSet.FirstOrDefault(b=>b.Id == A.BId);
    // do stuff with B
}

But I wonder if this is a valid solution because if I somehow remove B from the database and add new B entities eventually a different B gets the same ID as the original B stored in A.

what is the best practice of something like this?

The good news is, that is not how identity generation works. It's a counter, old numbers do not get re-used.

However, you might want to consider not using database identities for this purpose, and using a GUID (or sequence-based number) stored in a separate column. Database identities are considered private information, and might not be future proof when you want to merge databases (for example).

Keeping things in sync can indeed be a bit painful when you have to take deletes into account, but that's what you get for storing data-related data outside the database :-).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM