【问题标题】:EF Databinding, editing, modifying, saving recordsEF 数据绑定、编辑、修改、保存记录
【发布时间】:2016-03-02 15:17:18
【问题描述】:

我需要一个 EF 示例代码来根据输入到搜索字段中的值填充我的客户表单控件。考虑到此表单上的组合已填充,用户可以通过在 textBox 上指定值来创建新记录或编辑现有记录。组合中填充了来自辅助表(如 Country、State、City 等)的数据库数据(名称)。 在客户表上,我只有这些名称的 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? 提前致谢。

【问题讨论】:

  • 您想知道如何为所有文本框设置数据绑定吗?这样,一旦您更新 drCustomer,所有文本框都会自动更新,当用户更新文本框时,您的 Customer 对象中的相关字段也会自动更新?确认这一点,我会给你发送一个代码 sn-p 并解释它是如何工作的。
  • 嗨开瓶器!不完全是,但听起来很有趣。你介意把sn-p发给我吗?提前致谢。顺便说一句,我使用的是 ADO.Net,现在我将所有代码转换为实体框架。

标签: c# entity-framework data-binding edit


【解决方案1】:

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

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

【讨论】:

  • 伙伴们好!抱歉回复晚了,但这里的互联网是少数人的商品;-D....史蒂夫,您的建议“有效”,谢谢。但仅适用于 Int32、Guid 等标量类型。该方法假设使用主键列搜索记录。但我需要让用户能够使用其他标准(如 lastName、zip 等)进行搜索,这些标准代表表格上的正常字段。我需要类似的东西: var customer = context.Customers.FindIn(Column name, value to search);提前致谢。
  • 好的,我发布了问题中示例的 LINQ 等效项。如果你想要更动态的东西,我用一种方法编辑了答案。
  • 每次有人在 EF、LINQ 等上帮助我编写代码 sn-p 时,我都会对这些技术的功能感到非常兴奋。我在这两个方面都是新手......非常感谢史蒂夫和任何愿意提供帮助的人。
猜你喜欢
  • 2016-11-26
  • 1970-01-01
  • 2010-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多