处理仅使用类的几个属性的正确方法
本文关键字:几个 属性 方法 处理 | 更新日期: 2023-09-27 18:05:53
我正在添加一个相当大的程序。在这个程序中,有一个从数据库映射的类,它包含每个雇员的所有属性。它包含姓名、电话号码、雇佣日期等信息;超过40个属性。
现在,出于我个人的需要,我需要访问这些数据,但我只需要使用其中的四到五个属性,而不是所有可用的属性。我将以多种方式操作这个"迷你对象",例如搜索、返回结果等。这里有一个小的,自编的例子来补充我的解释。
public class BigEmployee //mapped from database
{
public string attr1 {get;set;}
public string attr2 {get;set;}
public string attr3 {get;set;}
public string attr4 {get;set;}
//...etc, until attribute 40
}
public class SmallEmployee //IF THIS EXISTED, this all that I would need
{
public string attr1 {get;set;} //same as BigEmployee attr1
public string attr2 {get;set;} //same as BigEmployee attr2
public string attr3 {get;set;} //same as BigEmployee attr3
}
和一个示例方法:
public List<SmallEmployee> GetAllEmployees
{
return EmployeeList;
}
所以,我想知道的是,我如何处理这个问题?我应该做一个单独的对象是从主类拉?我应该每次都访问主类并强制它只返回某些属性吗?
根据你提供的信息,你的问题不容易回答。不过,我会试着给出一些一般性的指导:
看起来你的项目正在使用某种形式的ORM,无论是第三方ORM (Entity Framework, NHibernate, SimpleData等)中的一个还是自己开发的。如果是这样的话,那么在它自己的类中创建同一个实体的"精简"版本实际上并没有什么错。orm生成的类应该只是DTO(数据传输对象),因此它们中不应该包含任何业务逻辑。使用这样的类的好处是,根据ORM,它们可以减少数据库流量(因为它们只恢复您使用的列)。
BUT(这是一个很大的但是)
它们只适合只读使用
大多数ORM依赖于将整个对象或对象图保存回数据库。它们通常不提供在内存中没有完整orm兼容实体形式的原始对象的情况下对数据库进行更改的方法。这些"生活"类最常见的用途是向用户发送大的对象列表,此时它们将以您的程序惯用的方式选择一个对象,然后程序将检索完整的实体对象进行编辑。
如果您需要的是完整的双向支持(检索以及插入、更新和删除功能),那么实际上您只能使用完整的实体类。
EDIT下面是一个使用"lite"实体的例子:
假设我们的上下文中有一个名为Customer
的实体。我们需要一个只包含ID(一个int
)和名称(一个string
)的lite客户。只需为生命体定义一个类:
public class CustomerLite
{
public int CustomerId { get; set; }
public string Name { get; set; }
}
然后在如下查询中使用:
var liteCustomers = context.Customers
.Where(c => c.Name.StartsWith("Smith, ")
.Select(c => new CustomerLite()
{
CustomerId = c.CustomerId,
Name = c.Name
})
.ToList();
(或者,如果您更喜欢查询语法而不是lambda语法)
var liteCustomers = (from c in context.Customers
where c.Name.StartsWith("Smith, ")
select new CustomerLite()
{
CustomerId = c.CustomerId,
Name = c.Name
}).ToList();
是的,这是一个很好的方法。如果您想直接从数据库作为查询返回它,这是一种方法。
另一个方法是使用接口:public interface ISmallEmployee
{
string attr1 {get;set;} //same as BigEmployee attr1
string attr2 {get;set;} //same as BigEmployee attr2
string attr3 {get;set;} //same as BigEmployee attr3
}
public class BigEmployee : ISmallEmployee
{
...
}
然而,ORM可能不会直接识别这一点,所以您必须查询所有BigEmployee
并将它们转换为c#中的ISmallEmployee
。
您也可以使SmallEmployee
成为BigEmployee
的基类,您需要在如何配置ORM来解释此
我想你是对的。
在SOLID中查找Ihttp://www.codeproject.com/Articles/60845/The-S-O-L-I-D-Object-Oriented-Programming-OOP-Prin
将主对象映射到客户端需要的投影