C#DTO只读属性 [英] C# DTO with read only property

查看:268
本文介绍了C#DTO只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类:

[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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆