Can we use enums as typesafe entity ids?

前端 未结 5 809
离开以前
离开以前 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 10:43

    It's an interesting approach, but the question is: is it worth it and what are the consequences?

    You could still do something like

     if ((int)blog.BlogId == (int)comment.CommentId) { }
    

    Personally I would invest more time in educating people, writing good tests, and code reviews, instead of trying to add some form of extra complexity that influences the way you use and query your entities.

    Think - for example:

    • What effect does this casting have on performance in LINQ queries?
    • How would you enforce this if you expose your operations through Web API of WCF?
    • Does this work with navigation properties??
    • Also, you are limited in the types you could use as primary key; I don't believe this works with Guids.

    A way of additional protection is to have your domain layer handle these kinds of things by accepting entity instances instead of ID's.

提交回复
热议问题