ComboBox选择不更新模型

时间:2017-09-08 09:51:57

标签: c# wpf entity-framework combobox

我有一个名为PhoneRecords的模型,其上有两个属性,一个CostCodeId(在数据库中)和CostCode通过CostCodeId与之关联,由Entity Framework创建。我有一个ComboBox,用户可以选择CostCode,我希望他们能够更新它。这是ComboBox

<ComboBox Grid.Row="5" Grid.Column="1" 
            ItemsSource="{Binding AllCostCodes}"
            DisplayMemberPath="Text" 
            IsSynchronizedWithCurrentItem="True"
            SelectedItem="{Binding SelectedRecord.CostCode}"/>

我像这样更新PhoneRecord(SelectedRecord):

using (var context = new DashboardContext())
{
    var original = context.PhoneRecords.FirstOrDefault(c => c.Id == SelectedRecord.Id);
    if (original == null) return false;
    context.Entry(original).CurrentValues.SetValues(SelectedRecord);
    return context.SaveChanges() > 0;
}

现在,当我深入研究SelectedRecord后,在用户选择CostCode中的其他ComboBox后,CostCode属性与PhoneRecord相关联已更新,但CostCodeId尚未更新。因此,context.SaveChanges()始终返回0,因为它未检测到属性已更新。

我的问题是如何将CostCode上选定的ComboBoxSelectedRecord.CostCodeSelectedRecord.CostCodeId对齐?

编辑:PhoneRecord.cs由EF生成:

public partial class PhoneRecord
{
    public int Id { get; set; }
    public Nullable<System.DateTime> DateGiven { get; set; }
    public string PersonName { get; set; }
    public Nullable<int> PhoneModelId { get; set; }
    public Nullable<bool> NMU { get; set; }
    public string IMEI { get; set; }
    public string Number { get; set; }
    public Nullable<int> CostCodeId { get; set; }
    public Nullable<System.DateTime> DateReturned { get; set; }
    public string WhyReturned { get; set; }
    public string Solution { get; set; }
    public string Internet { get; set; }
    public string Provider { get; set; }
    public string SpeedDial { get; set; }
    public string OnDatabases { get; set; }
    public string Notes { get; set; }

    public virtual CostCode CostCode { get; set; }
    public virtual PhoneModel PhoneModel { get; set; }
}

1 个答案:

答案 0 :(得分:1)

ComboBox控件设置一个属性。该逻辑应该在PhoneRecords类中实现。像这样:

public partial class PhoneRecord
{
    private CostCode _costCode;
    public CostCode UiCostCode
    {
        get { return _costCode; }
        set
        {
            _costCode = value;
            CostCodeId = _costCode != null ? _costCode.CostCodeId : 0;
        }
    }
}