29

I'm just starting out with Entity Framework and I'm concerned about the ease with which a primary key can be overridden. I know I can protect this model in my controller (I'm using WebAPI with ASP.NET MVC 5), but I am wondering if it is possible to prevent anyone setting the ID of my model from the model itself via annotations or something?

Basically can I do this:

public int ID { get; private set; }

or something similar, in an EF6 model?

If this is easily found through Google then I don't know the terms to search. I've not been able to find anything that really answers this.

4
  • 2
    It looks like you can. I just tried it with my Mvc Movie tutorial application from the asp.net site. If you are not sure if it will work and google search fails, then try it out! But asking questions doesn't hurt either :P.
    – John Odom
    Commented Nov 5, 2014 at 22:55
  • Ya, I should have. I just want to see some documentation out there on it and hoped the question would make a good place for it to live next time someone looks. Please add an answer if you could. Thanks! Commented Nov 5, 2014 at 22:56
  • I guess anyone who knows Reflection can set this "ID" thing.
    – themefield
    Commented Dec 31, 2020 at 23:12
  • Yup, but if you're playing around with Reflection you should be aware that you're circumventing any protections the language was trying to provide :) Commented Feb 2, 2021 at 21:27

1 Answer 1

39

Yes you can, and it should work just fine. Per this blog post by Julie Lerman (who's Microsoft's Entity Framework MVP, so I highly recommend that you read her blog on your journey through EF!):

Entity Framework requires a parameterless constructor in order to materialize objects returned from queries (or loading). I have made this concession in my class but notice that it is a private constructor. So I’m still protecting my class. Nobody can access it. But EF is still able to populate this class when I execute queries. And no, I’m not doing some magic to tell EF to use my public constructor. It really uses the private constructor.

1
  • 7
    Julie Lerman is my automatic go-to on things like this. I literally just searched "Julie Lerman private set" without even knowing if she'd talked about it already. Commented Nov 5, 2014 at 23:02

Not the answer you're looking for? Browse other questions tagged or ask your own question.