私のDALはDataTablesを返すべきですか、それとも私は何でも<&gt ;?
-
08-07-2019 - |
質問
編集1
おizeび申し上げますが、提案された2つの記事を読んだ後、何を使うべきか理解できません。 IQueryableを使用することはさまざまな理由で優先されないことを理解していますが、IEnumerableも排除されますか? DataTableは本当に私の最良の選択肢ですか?
要するに、私が思うに、好ましい戻り型は何ですか?
DALに抽象化する次の簡単なLINQクエリがあります。 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);
}
解決
彼が意味するのは、DALに返すオブジェクトにデータをマッピングすることです。
最初の質問&quot; var&quot;への回答実際には変数の略であり、型は代入で定義されている型です。
var myvariable = string.empty;
この例では、型は文字列の型です。
var myreader = new StringReader();
この例では、型はStringReaderの型です。
&quot;とは&quot;の2番目の質問について。 Tはジェネリック型です。
dalが実際のオブジェクトを返す場所の例:
public Product GetProduct(int ProductID)
{
var product = from p in db.MyTable
where p.productID == ProductID
select new product { name = p.name, pricepoint = p.pricepoint, qty = p.quantity };
return product;
}
他のヒント
まず、IQueryableはIEnumerableを実装しているため、両方が表示される可能性があります。 詳細についてはこちら
をご覧ください。一般に、可能であれば、DALが実際のオブジェクトを返すことをお勧めします。
読むこのブログでは、提案されていることを行う方法としない方法のガイドラインについて説明しています。短い答え、IQueryableを返さないでください。
編集: 例:
internal static File[] GetAllFilesByUserID(int userID)
{
var db = GetDataContext();
return (from files in db.Files where files.OwnerUserID == userID select files).ToArray();
}