Can we use enums as typesafe entity ids?

前端 未结 5 811
离开以前
离开以前 2021-02-05 10:21

We are working with a rather large model in a EF 6.1 code first setup and we are using ints for entity ids.

Unfortunately, this is not as typesafe as we would like, sinc

5条回答
  •  野的像风
    2021-02-05 11:05

    I really don't try to bash you, but how can one mix up Ids of Type X with Ids of Type Z? I never met anybody who did stuff like myBlog.Id++ either (or at least not without getting fired).

    Anyhow, here is a solution which seams to be less work and better maintainable (especiall for the db-admins):

    -In the TypeConfiguration, create an Id through the fluent API (you'll see why later)

    -Create an abstract base-class for all your entities with:

    *property: proteced int Id

    *method: public int getIdValue()

    *method: public bool isSameRecord(T otherEntity) where T: EntityBaseClass

    I guess the first method are self-explanatory, the isSameRecord will take the other instance of your base-class, does a type-check first and if it passes it, it will do a id-checkup, too.


    This is an untested approach, there's a good chance you can't create protected identifiers.

    If it doesn't work, you could create public int _id and just tell your team to not use it directly.

提交回复
热议问题