在linq结果中插入额外的数据,但不插入数据源,或等待对上下文对象提交更改 [英] Inserting extra data in a linq result but not to the data source or waiting for submiting changes on a context object

查看:84
本文介绍了在linq结果中插入额外的数据,但不插入数据源,或等待对上下文对象提交更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我有一个类型化的DataTable并具有从带有表适配器的SQL Server检索到的信息时,我可以将临时数据插入到我只想在执行时使用的DataTable中,而我不希望这样做插入数据库.
首先假设例如,我有一个像这样的数据库表:

When I had a Typed DataTable with information retrieved from a SQL Server with a table adapter, I'm able to insert temporary data into that DataTable which I just want to use on execution time, and I don't want it to be inserted into the database.
First supose that for example I have a Database table like this:

CREATE TABLE MyData
(
    MyCol1 int,
    MyCol2 nchar(10)
)

所以我使用SqlClient对象.

So using SqlClient objects this is what I do.

MyTypedDataSet.MyTypedDataTable myDataTable = 
    new MyTypedDataSet.MyTypedDataTable();
myDataAdapter.Fill(myDataTable);
myDataTable.NewMyTypedRow(value1, value2);

然后我可以将其绑定到控件,例如组合框

I then could bind this to a control, e.g. a ComboBox

myComboBox.DataSource = myDataTable;
myComboBox.DisplayMember = "myCol2";
myComboBox.ValueMember = "myCol1";

如何使用LINQ to SQL结果执行相同的操作,

How can I do the same with a LINQ to SQL Result such as:

var myQuery = from data in myContext.MyDatas
              select myCol1, myCol2;
myComboBox.DataSource = myQuery;

看,我想在myQuery中添加该额外的行,以便可以将此数据绑定到我的组合框,但是我不希望在数据库中该额外的行.
我通过调用ToList()方法来解决此问题,然后添加所需的数据,然后将此列表绑定到我的ComboBox,如下所示:

See, I want to add that extra row in myQuery, so that I can bind this data to my combo box, but I don't want that extra row in my database.
I worked around it by calling the ToList() method, then I add the data I want, and then I bind this list to my ComboBox, like this:

var myList = myQuery.ToList();
myList.Insert(0, new MyData() { myCol1 = value1, myCol2 = value2 });
myComboBox.DataSource = myList;

...但是如何将其直接插入到myQuery中呢?这是一个好习惯吗?还是我的解决方法是正确的选择?

... But how can I do this insert directly into myQuery? would it be a good practice? or my workaround would be the right thing to do?

PS:顺便说一句,当我过去将类型化的数据表绑定到ComboBoxes时,我将使用模式生成的名称将值分配给DisplayMemberValueMember,如下所示:

PS: By the way, when I used to bind typed data tables to ComboBoxes I would use the schema generated names to asign values to DisplayMember and ValueMember like this:

myComboBox.DisplayMember = myDataTable.myCol1Column.ColumnName;
myComboBox.ValueMember = myDataTable.myCol2Column.ColumnName;

如何从myQuery中提取此信息?

推荐答案

我认为您在做什么很好.

I think what you're doing is fine.

另一种方法是创建一个包含一个元素的新列表,然后使用

An alternative is instead of creating a list and inserting into it, you could create a new list containing one element and use the Concat method to concatenate the remaining elements. This can be a LINQ one-liner. But your way is probably more readable, so maybe just stick with that.

这篇关于在linq结果中插入额外的数据,但不插入数据源,或等待对上下文对象提交更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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