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

本文关键字:保存 记录 修改 编辑 数据绑定 EF | 更新日期: 2023-09-27 18:37:06

我需要 EF 示例代码来根据搜索字段中输入的值填充我的客户窗体控件。考虑到此窗体上的组合已填写,用户可以创建新记录或通过在 textBox 上指定值来编辑现有记录。组合中填充了来自国家、州、城市等辅助表的数据库数据(名称)。在客户表上,我只有这些名称的 Id(外键)。因此,当用户输入客户 ID 时,在表单上,如果它不存在,我们将创建一个新记录,否则表单应从数据库加载整个记录并填写表单上的相应字段,包括在组合上显示与记录上的 ID 匹配的名称,为用户提供修改任何字段并将其保存回的选项。 在非 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?提前谢谢。

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

假设您的数据上下文有一个变量,比如上下文:

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();