Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can private setters be used in an entity model?

Tags:

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.

like image 779
OneHoopyFrood Avatar asked Nov 05 '14 22:11

OneHoopyFrood


People also ask

What is a private setter?

Private setter means the variable can be set inside the class in which it is declared in. It will behave like readonly property outside that class's scope. Read only property can only be accessed, not mutated.

Can entities have constructors?

It's possible to define a constructor with parameters and have EF Core call this constructor when creating an instance of the entity. The constructor parameters can be bound to mapped properties, or to various kinds of services to facilitate behaviors like lazy-loading.

What is the use of private set in C#?

The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To achieve this, you must: declare fields/variables as private. provide public get and set methods, through properties, to access and update the value of a private field.


Video Answer


1 Answers

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.

like image 200
Corey Adler Avatar answered Oct 05 '22 15:10

Corey Adler