CBreeze
CBreeze

Reputation: 2965

ComboBox Selection not Updating Property on Model

I have a model called PhoneRecords that on it has two Properties, a CostCodeId (in the database) and a CostCode that is associated with it through the CostCodeId, created by Entity Framework. I have a ComboBox where the user can select a CostCode and I want them to be able to update it. This is the ComboBox:

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

I update the PhoneRecord (SelectedRecord) like so:

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;
}

Now when I delve into the SelectedRecord, after the User has chosen a different CostCode in the ComboBox, the CostCode property associated with the PhoneRecord has updated but the CostCodeId has not. As a result the context.SaveChanges() always returns 0 as it does not detect that the property has been updated.

My question is how can I align the CostCode selected on the ComboBox to both the SelectedRecord.CostCode and the SelectedRecord.CostCodeId?

EDIT: PhoneRecord.cs Generated by 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; }
}

Upvotes: 0

Views: 49

Answers (1)

mm8
mm8

Reputation: 169200

The ComboBox control sets one property. This logic should be implemented in the PhoneRecords class. Something like this:

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

Upvotes: 1

Related Questions