C#DTO只读属性 [英] C# DTO with read only property
问题描述
我有以下类:
[DataContract()]
public partial class User
{
[DataMember()]
public int Id { get; set; }
[DataMember()]
public string Name { get; set; }
[DataMember()]
public string Surname { get; set; }
}
我的DTO类在一个程序集中,而我的模型(EF)另一个。因此,所有属性必须是public get / set。
My DTO classes are in one assembly and my model (EF) is in another. Therefore all properties must be public get/set.
Id是一个标识列,由数据库设置并且也被自动化。但是我不希望用户更改ID。
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.
是否可以在属性上设置属性,以便在用户正在使用该属性时将属性设置为只读dto?
Is it possible to set an attribute on the property that sets the property to readonly when the user is working with the dto?
推荐答案
在定义访问器时,您可以随时访问属性。在你的代码中使用 Id
。这可能是这样的:
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; }
你不能使属性的getter / setter比属性更少限制本身,例如
You cannot make a property's getter/setter less restrictive than the property itself, e.g.
[DataMember]
private int Id { public get; set; }
这篇关于C#DTO只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!