实体edmx中的组合框

时间:2010-11-03 22:20:02

标签: entity-framework edmx

我是c#的新手。我有一个关于组合框与实体edmx对象中的外键绑定的问题。

我有“客户卡”edmx实体对象,其中包含字段,其中一个字段是此客户的外键(CityID),其中包含Cities列表或“City”实体对象的ID。

我想在我的代码中管理客户City组合框。我正在填充组合框。当用户保存记录时,还检索当前选定的项目。然而;我不知道如何将组合项目中的选定项目分配回Customer实体对象。我在实体对象中看到的只是City和CityReference属性。我的问题是如何将当前城市ID选择项分配给实体对象中的“客户卡”?请包含代码。

这是我的代码

    private class CustCard
    {
        public int ID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string City { get; set; }
    }

    public class CityCard
    {
       public int ID {get; set;}
       public string Name {get; set;}
       public string Country {get; set;}
    }

    var custCards = from p in entities.CustomerCards
                        select new CustCard
                        {
                            ID = p.ID,
                            CompanyName = p.CompanyName,
                            ContactName = p.ContactName,
                            City = p.City.Name,
                            CityID = p.City.ID,
                        };

    var cityList = from p in entities.Cities
                       select new CityCard
                       {
                            ID = p.ID,
                            Name = p.Name,
                            Country = p.Country.Name,
                       };

    //Bind City List
    CityComboBox.DataSource = CityList; //cities in the entity object
    CityComboBox.ValueMember = "ID";
    CityComboBox.DisplayMember = "Name";

    private void Save_Click(object sender, EventArgs e)
    {
            CustomerCard Cust = new CustomerCard();

            Cust.Address = addressTextBox.Text;
            Cust.CompanyName = companyNameTextBox.Text;


            **// HOW CAN I assign Selected item to the City field in the CustCard
            ????????????cityIDComboBox.SelectedItem;?????????????**

            entities.AddToCustomerCards(Cust);
            entities.SaveChanges();
    }

2 个答案:

答案 0 :(得分:0)

怎么样......

Cust.City = CityComboBox.SelectedItem.Name;

答案 1 :(得分:0)

  private void Save_Click(object sender, EventArgs e)
    {
            CustomerCard Cust = new CustomerCard();

            Cust.Address = addressTextBox.Text;
            Cust.CompanyName = companyNameTextBox.Text;


            Cust.City = CityComboBox.SelectedItem.Name;
            Cust.CityID = CityComboBox.SelectedItem.Value;

            entities.AddToCustomerCards(Cust);
            entities.SaveChanges();
    }