具有大量参数的 DAL 方法

本文关键字:DAL 方法 参数 | 更新日期: 2023-09-27 18:35:16

我的 DAL 中有几个方法,有很多参数:

public Collection<Proforma> SearchAllProforma(DateTime? startDate = null, DateTime? endDate = null,
        int? institutionID = null, int? inspectionID = null, bool? isFollowup = null, bool? excludeDeleted = null,
        bool? nutritionalOnly = null, int? parentInspectionID = null)

我应该压缩这些内容以采用对象参数吗?或者使用可选参数保持原样?还是两者兼而有之?

编辑 - 我真的应该说,这些参数中的每一个都映射到存储过程的参数。

具有大量参数的 DAL 方法

我建议您为所有这些参数创建一个类作为属性。

然后将类作为参数发送。

Class SerachAllProformaParameter
{
//All Properties.
}
SerachAllProformaParameter parameter= new SerachAllProformaParameter();
parameter.PropertyName="value";
public Collection<RoIVProforma> SearchAllProforma(parameter);

我应该压缩这些内容以采用对象参数吗?

不一定。默认值似乎没问题(我假设您的函数可以毫无问题地处理null参数)。如果使用的是最新版本的 C#,则可以调用此函数,如下所示:

SearchAllProforma(institutionID: 33);

在我看来,这并不是那么糟糕。

考虑到其中很多都有其默认值,为了提高可用性,我会使用不同数量的参数添加此方法的几个覆盖

这样,对于您的方法的使用者来说,选择合适的方法将更容易,而无需在智能感知窗口中看到所有参数

public Collection<RoIVProforma> SearchAllProforma(DateTime? startDate = null) 
{
   ...
}
public Collection<RoIVProforma> SearchAllProforma(DateTime? startDate = null, DateTime? endDate = null)
{
 ...
}
public Collection<RoIVProforma> SearchAllProforma(DateTime? startDate = null, DateTime? endDate = null,
        int? institutionID = null)
{
 ...
}
...

我应该压缩这些内容以采用对象参数吗?

是的,绝对。看着这个方法签名,我的眼睛开始流血。

使用对象作为参数,这是一个很好的方法。

如果所有参数都属于您的某个实体,则可以将谓词 lambda 表达式传递给该方法。

我使用以下方法在我的实体中搜索一些条件。

public List<Personel> GetAll(Func<Personel, bool> predicate = null)
        {
            List<Personel> result = new List<Personel>();
            if (predicate == null)
            {
                result = personelRepo.Table.ToList();
            }
            else
            {
                foreach (var item in personelRepo.Table)
                {
                    if (predicate(item))
                        result.Add(item);
                }
            }
            return result;
        }

然后在调用时将谓词传递给该方法,如下所示:

var myFilteredEntities = GetAll(e => e.Name == "John" && e.IsMarried == false);

就个人而言,最好的方法是将Expression<Func<RoIVProforma, bool>>实例传递到 SearchAllProforma 方法中。但是,如果 DAL 不使用任何基于 LINQ 的基础数据源,则实现分析表达式会更加困难。
同时,具有许多可选参数的方法是最差的。