问题
I have the following class:
[DataContract()]
public partial class User
{
[DataMember()]
public int Id { get; set; }
[DataMember()]
public string Name { get; set; }
[DataMember()]
public string Surname { get; set; }
}
My DTO classes are in one assembly and my model (EF) is in another. Therefore all properties must be public get/set.
The Id is an identity column and is set by the db and also automapped. However I don't want that the user changes the id.
Is it possible to set an attribute on the property that sets the property to readonly when the user is working with the dto?
回答1:
You can always make the access of properties more specific as you define the accessors. Using Id
from your code. That could look like this:
[DataMember]
public int Id { get; private set; }
You cannot make a property's getter/setter less restrictive than the property itself, e.g.
[DataMember]
private int Id { public get; set; }
回答2:
You could use a protected set:
[DataMember()]
public int Id { get; protected set; }
and ensure the fields are only set in the constructor...
回答3:
[DataMember()]
public int ID{ get; private set; }
来源:https://stackoverflow.com/questions/20240563/c-sharp-dto-with-read-only-property