Why have a private setter in essence

Still used to the Entity framework, but I saw the code as shown below where they have a private setter for id in Entity.

public int Id { get; private set; } public string FirstName { get; set; } public string LastName { get; set; } 

Why does anyone have a private setter. In any case, this identifier field is automatically generated in the database, and is its personal reason for it?

Also, why do we need a private constructor and a public constructor in essence, as shown below?

 private Emp() { } public Emp(string name, string lastname) { FirstName = firstname; LastName = lastname; } 
+6
source share
3 answers

You do not need to set the value of the primary column yourself, precisely because it is automatically generated by the database, so why do you need to do something that does not make sense? Therefore, you are making the Id setter private. EF can still set this property when materializing an object, even if it is private.

The same story with the designer. EF requires your organization to have a parameterless design, but it can be private. But you do not want (in your example) to create an entity for the user without providing a first and last name, because most likely these names are required and you want this to be explicitly expressed. Thus, you have one constructor for creating an object (with both names) and one for EF to materialize the object obtained from the database (without parameters).

Note that both the private setter and this constructor configuration are in no way required by EF. All this is done for the convenience of developers to prevent unwanted behavior (setting the Id field or creating an Emp object without providing names).

+8
source

A private setter is useful for granting a user read-only rights, meaning that he will not allow you to modify it. Since some properties, such as ID , you do not want it to be changed, or if you want to add some checks or set the property at the class level (from a class with a class). In this case, we use a private setter.

 public int Id { get; private set; } 

or several times, for example

 private int Id ; public int Id { get { return Id ; } } 
+4
source

In addition to the answers provided, with the introduction of C # 6.0, you no longer need private installers to set the property value.

You can use the following code instead of private settings:

 public class Appointment { public DateTime TimeStamp { get; } = DateTime.UtcNow; public string User { get; } = System.Security.Principal.WindowsPrincipal.Current.Identity.Name; public string Subject{ get; } = "New Subject" } 

You can check here for more information.

As for a private constructor: private constructors are used, you do not want the class to be created by code outside the class. Singletons , factories , static method objects are examples of where it is useful to restrict the constructor.

+1
source

Source: https://habr.com/ru/post/1015428/


All Articles