简体   繁体   English

实体框架和持有ID

[英]Entity Framwork and holding IDs

I work with the Entity Framework and C# and have the following problem. 我使用实体框架和C#,遇到以下问题。 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. 因此,如果我有一个对象A和一个实体BI将B的ID存储在A中。然后我对A进行填充,最终想再次访问B。 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. 但是我想知道这是否是一个有效的解决方案,因为如果我以某种方式从数据库中删除B并添加新的B实体,最终另一个B将获得与存储在A中的原始B相同的ID。

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. 但是,您可能要考虑不要为此目的使用数据库身份,而要使用存储在单独列中的GUID(或基于序列的编号)。 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 :-). 当您必须考虑删除操作时,保持事物同步确实会有些痛苦,但这就是在数据库外部存储与数据相关的数据时所要付出的努力:-)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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