0

使用实体框架如何选择要在文本框中显示的任何字符串。过去使用 myReader 我会执行以下操作:

while (myReader.Read())

{
 string sName = myReader.GetString(1);
 txtName.Text = sName;
}
4

1 回答 1

0

您必须加载所需的实体(=表),然后将实体的属性分配给文本框。

就像是:

using (var myContext = new EntityContext())
{
myContext.TableName.Load(); //this will load all rows from the table

var list = myContext.TableName.Local; //.Local is a list of the entities which gets populated when you cann the Load() method

//now you can either enumarte your list like so
foreach (TableName item in list)
{
string sName = item.PropertyName; //PropertyName is the property you want to display, this would be like using not an index in myReader.GetString(1) but the columnname myReader.GetString("ColumnName")
txtName.Text = sName;
}

//or if you want to get a certain item out of your list you can use LINQ/MethodChains
//MethodChain
var item = list.First(x => x.PropertyName == "HelloWorld!");
string sName = item.PropertyName;
txtName.Text = sName;

//LINQ
var item = (from x in list
            where x.PropertyName == "HelloWorld!"
            select x).First();

string sName = item.PropertyName;
txtName.Text = sName;

//the methodchain and linq is a "new" technology that simplifies this code (which does the same)
TableName item = null;
foreach (TableName tempItem in list)
{
    if (tempItem.PropertyName == "HelloWorld!")
    {
        item = tempItem;
        break;
    }
}

string sName = item.PropertyName;
txtName.Text = sName;

}

于 2013-10-31T15:47:54.263 回答