EF数据绑定,编辑,修改和保存记录

问题描述:

我需要一个EF示例代码来填充我的客户表单控件,该控件基于放置在搜索字段中的值。考虑到这个表单上的组合已经被填充,并且用户可以通过在文本框上指定一个值来创建新记录或编辑现有的记录。组合中充满了来自国家,州,城市等辅助表的数据库数据(名称)。 在客户表上,我只有这些名称的Id(外键)。因此,在用户放置客户ID的表单上,如果它不存在,我们正在创建一个新记录,否则表单应该从数据库加载整个记录并填写表单上的相应字段,包括在组合与记录上的Id相匹配的名称,为用户提供修改任何字段并将其保存的选项。 在非EF情况下我会是这样的:EF数据绑定,编辑,修改和保存记录

private void txtId_TextChanged(object sender, EventArgs e) 
    { 
     sqlStrQuery = "Select FName, LName, Email, Phone, CountryId from Customer where ID= '" + txtId.Text + "'"; 
     SqlCommand sqlCmd = new SqlCommand(sqlStrQuery, sqlConStr); 

     sqlConStr.Open(); 
     SqlDataReader drCustomer = sqlCmd.ExecuteReader(); 
     if (drCustomer.HasRows) 
     { 
      while (drCustomer.Read()) 
      { 
       txtFirstName.Text = drCustomer.GetValue(1).ToString(); 
       txtlastName.Text = drCustomer.GetValue(2).ToString(); 
       txtEmail.Text = drCustomer.GetValue(3).ToString(); 
       txtPhone.Text = drCustomer.GetValue(4).ToString(); 
       cboCountry.SelectedValue = drCustomer.GetValue(5); 

      } 
     } 

    } 

我怎么能转换成EF? 在此先感谢。

+0

你想知道如何设置绑定您的所有文字盒子?这样,一旦您更新drCustomer,所有文本框会自动更新,并且当用户更新文本框时,您的Customer对象中的相关字段也会自动更新?确认这一点,我会发给你一个代码片段,并解释它是如何工作的。 –

+0

嗨Opender!不完全,但这听起来很有趣。你介意给我一小段代码吗?提前致谢。顺便说一句,我使用ADO.Net,现在我将我所有的代码转换为实体框架。 –

+0

即将做:) –

假设你有一个变量,比如背景,为您的数据方面:

var customer = context.Customers.Find(txtId.Text); 
if (customer != null) 
{ 
    txtFirstName.Text = customer.FirstName; 
    txtlastName.Text = customer.LastName; 
    txtEmail.Text = customer.Email; 
    txtPhone.Text = customer.Phone; 
    cboCountry.SelectedValue = customer.CountryId; 
} 

编辑:要搜索多个标准

var matches = context.Customers.AsQueryable(); 
if (!string.IsNullOrEmpty(txtLastName.Text)) 
{ 
    matches = matches.Where(m => m.LastName == txtLastName.Text); 
} 
if (!string.IsNullOrEmpty(txtFirstName.Text)) 
{ 
    matches = matches.Where(m => m.FirstName == txtFirstName.Text); 
} 
// repeat for searchable fields 
return matches.ToList(); 
+0

嗨,伙伴!对不起,迟到的回复,但互联网在这里是一个选择少数商品; --D .... 史蒂夫,你的建议“有效”,谢谢。但只适用于像Int32,Guid等标量类型。该方法假定使用主键列搜索记录。但我需要为用户提供使用其他标准(如lastName,zip等)进行搜索的可靠性,这些标准表示表中的正常字段。我需要类似于: var customer = context.Customers.FindIn(列名,要搜索的值); 在此先感谢。 –

+0

好的,我发布了问题中示例的LINQ等价物。如果你想要更有活力的东西,我用一种方法编辑答案。 –

+0

每次有人用EF,LINQ等代码片断帮助我,我对这些技术的功能感到非常兴奋。我对这两个人都是新的......史蒂夫和任何不愿意帮助的人都很荣幸。 –