Display Name
Display Name

Reputation: 15091

Should the setter of a property for an entity model class be set to private?

As the primary key PassageId will be created automatically and cannot be changed, exposing the setter of PassageId does not make sense (at least to me). Should the setter of PassageId be set to private?

public class Passage
{
    public int PassageId { get; private set; }
    public string Contents { get; set; }

    public DateTime CreatedUtc { get; private set; }
    public DateTime ModifiedUtc { get; private set; }
}

Note

Most tutorials I read, the authors always use the default properties generated by Visual Studio's shortcut prop enter (twice) producing something like

public type PropertyName {get; set;}

So I am wondering why they didn't make the setter private.

Upvotes: 2

Views: 882

Answers (1)

Steve Padmore
Steve Padmore

Reputation: 1740

This is because usually (design-wise), the entity is an object that you will pass around for displaying data or updating it.

Therefore, when the entity is instantiated, you need to populate the properties with the data from storage (or from the presentation layer's input).

E.g. Person person = PersonService.GetById(personId);

Given that the PersonService calls through to the Entity Framework and finds the single Person record where the Id matches personId, it will then populate that 'person' entity with the values retrieved.

For Entity Framework to populate the entity the fields need to be publicly settable.

If via code or user input, the person's name is changed, the Id will be used on the SaveChanges() method for the update.

When inspecting an entity's properties:

If the Id is 0, then it will be treated as a new entity and should be 'Added' to storage on SaveChanges().

If the Id is > 0 then it should be Updated on SaveChanges().

If the Id field was to be set privately, after populating the rest of the properties, the class would then need a way (internally) to get the Id of the current entity from elsewhere - wouldn't make much sense.

Upvotes: 1

Related Questions