C# DTO with read only property

一世执手 提交于 2019-12-11 13:54:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!