我有一个名为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
上选定的ComboBox
与SelectedRecord.CostCode
和SelectedRecord.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; }
}
答案 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;
}
}
}