如何在C#中基于场景有效地使用DTO [英] How to use the DTO efficiently based on Scenario in C#

查看:630
本文介绍了如何在C#中基于场景有效地使用DTO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Employee模型,它包含有关Employee的所有信息

I'm working on Employee Model, it contains all the information about the Employee

例如:

public class Employee
{
    public int EmployeeId { get; set; }
    public string FirstName { get; set; }
    public string MiddleName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string HomePhone { get; set; }
    public string MobilePhone { get; set; }
}

我有两种方法来获取Employee的记录

I'm having two methods for fetching records of Employee

public Employee GetEmployeeName(int id)
{
    // The return should contain only FirstName, MiddleName and LastName. 
    // The rest of the properties should be non-accessable (i.e., Private)
}

public Employee GetEmployeeContacts(int id)
{
    // The return should contain only EmailAddress, HomePhone and MobilePhone. 
    // The rest of the properties should be non-accessable (i.e., Private)
}

public Employee GetEmployeeNameEmail(int id)
{
    // The return should contain only FirstName, MiddleName, LastName and EmailAddress. 
    // The rest of the properties should be non-accessable (i.e., Private)
}

public Employee GetEmployee(int id)
{
    // It should return the entire Employee object
}

我该如何实现?您能在这方面请任何人帮忙吗?

How could I achieve this? could you please any one help in this regards.

推荐答案

简单的答案是,您不能将对象属性的可见性从一个实例更改为另一个实例-它们是类定义的.您可以执行以下操作之一:

The simple answer is that you cannot change the visibility of an object's properties from one instance to another -- they are whatever the class defines. You can do one of the following:

  1. 使用动态对象,它具有许多优点和缺点.请参见此处使用继承定义一个基类(例如EmployeeCommon),该基类具有您要从各种方法返回的每个其他子集(EmployeeCommonAndPhoneNumbers)的公共分母属性和子类.

    Use inheritance to define a base class (e.g. EmployeeCommon) with the common denominator properties and subclasses for each additional subset (EmployeeCommonAndPhoneNumbers) you want to return from your various methods.

    将各种属性集分离到单独的属性组"类(例如,ContactInfo)中,并将它们作为属性放在您的Employee类中.您想要显示和隐藏"的单个属性(例如FirstNameEmailAddress)可以根据需要在Employee的每个实例上存在或不存在,但是所有各种属性组"对象仍将处于启用状态. Employee的每个实例都作为属性(尽管在不需要的实例上它们将是null),所以这可能符合或可能不符合您的要求.

    Separate out the various sets of properties into separate "property group" classes (e.g. ContactInfo), and put them as properties on your Employee class. The individual properties (like FirstName or EmailAddress) that you want to "show and hide" can be present or absent on each instance of Employee as you need, but all of the various "property group" objects would still be on every instance of Employee as a property (though they would be null on the instances where they're not needed), so this may or may not fit your requirements.

    这篇关于如何在C#中基于场景有效地使用DTO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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