Can we use enums as typesafe entity ids?

前端 未结 5 820
离开以前
离开以前 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 know I'm a bit late to this party, but I've used this technique and it definitely works!

    Type safety works exactly as you suggest. Compiler will catch mistakes such as

    from c in ctx.Comments where c.ParentPost.Blog.Id == currentUser.Id
    

    And it prevents silly maths.

    currentUser.Id++;
    currentUser.Id * 3;
    

    Navigation properties still work fine too, as long as both ends of the navigation are the same enum type.

    And the SQL queries work just as they do with an int.

    It's certainly an interesting idea!

    Can you use typesafe entity IDs? - Yes!

    Should you? I'm not sure. It doesn't seem that this is how EF was designed and feels a little hacky.

提交回复
热议问题