c# - 我的 DAL 应该返回 DataTables 还是我...随便<>?

标签 c# linq linq-to-sql n-tier-architecture

编辑 1

我很抱歉,但在阅读了 2 篇建议的文章后,我仍然不明白我应该使用什么。我知道由于各种原因不推荐使用 IQueryable 但这是否也消除了 IEnumerable ? DataTable 真的是我最好的选择吗?

简而言之,我想,首选的返回类型是什么?


我有以下简单的 LINQ 查询,我想将其提取到 DAL 中。 var 的类型是什么,因此我的方法应该是什么类型?

            ConnectDBDataContext context = new ConnectDBDataContext();

        var lName = textEdit1.Text;

        var searchByPersonLName = from c in context.tblPersons
                                  where c.LastName == lName
                                  orderby c.LastName
                                  select new { c.FirstName,c.LastName,c.PersonID};

        dataGridView1.DataSource = searchByPersonLName;

当我在 VS 中将鼠标悬停在它上面时,它会显示 IQueryable<T>但是当我放置一个断点并运行它时,它似乎 称自己为 IEnumerable。哪个是正确的,我应该如何声明我的方法?

像这样-->

        public static DataTable SearchPerson(string SearhParam)
    {
        ConnectDBDataContext context = new ConnectDBDataContext();
        var persons = (from person in context.tblPersons
                       orderby person.LastName
                       select new { person.PersonID, person.LastName, person.FirstName, person.SSN });
        var filteredPersonsList = persons.Where(p => p.LastName == SearhParam).ToList();
        if (filteredPersonsList.Count == 0)
            filteredPersonsList = persons.Where(p => p.LastName.StartsWith(SearhParam)).ToList();

        var dataTable = filteredPersonsList.CopyLinqToDataTable();

        return dataTable;
    }

如果我使用 IQueryable<T>什么是 <T>或者我怎么知道,我会返回什么?

谢谢!

下面是 CopyToDataTable() 作为引用。

public static DataTable CopyLinqToDataTable<T>(this IEnumerable<T> source)
    {
        return new ObjectShredder<T>().Shred(source, null, null);
    }

    public static DataTable CopyLinqToDataTable<T>(this IEnumerable<T> source,
                                                DataTable table, LoadOption? options)
    {
        return new ObjectShredder<T>().Shred(source, table, options);
    }

最佳答案

首先,IQueryable 实现了 IEnumerable,因此这就是您可能同时看到两者的原因。参见 here for more details

通常,我会建议您的 DAL 尽可能返回您的实际对象。

我会 read this blog有关如何做以及如何不做您建议的指南。简短回答,不要返回 IQueryable。

编辑: 示例:

        internal static File[] GetAllFilesByUserID(int userID)
    {
        var db = GetDataContext();
        return (from files in db.Files where files.OwnerUserID == userID select files).ToArray();
    }

关于c# - 我的 DAL 应该返回 DataTables 还是我...随便<>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/836621/

相关文章:

c# - 在字符串中的冒号之间添加空格

c# - 在 LINQ 查询上使用 "Include"方法时出错

c# - LINQ 自定义排序

c# - 比较不同列的值后返回字段的 ID

linq-to-sql - 是否可以在LinqToSql中使用Soundex(或其他SQL函数)?

c# - 比较不可为 null 的 `int` 与 `null` (LINQ)

Double.GetHashCode() 的 C# 缺陷

c# - 找不到类型或命名空间 'var'

c# - 非常基本的虚函数练习

c# - 代码好像没有通过某行,导致StackOverflowException