使用bindingnavigator和bindingsource为ef6创建了一个主要细节Winforms。
我能够检索并更新或添加子行到现有的行,但是当我从屏幕添加新的主记录和子记录时,它只更新master。儿童记录消失了。还注意到,当我更改任何主要细节时,儿童记录会消失。
如果我从后端添加一个子行,那么我可以在屏幕上编辑和添加新的子行。
我认为问题可能是由于新记录缺少外键,实体框架是否会将主密钥作为外键切换到详细信息,或者是否有任何值设置?
加载数据和数据绑定代码:
//
_context.Purchases.Include("PurchaseItems").Load();
purchaseBindingSource.DataSource = _context.Purchases.Local.ToBindingList();
//
purchaseItemsBindingSource.DataMember = "PurchaseItems";
purchaseItemsBindingSource.DataSource = this.purchaseBindingSource;
型号:
//
public class Purchase
{
public Purchase()
{
}
public int ID { get; set; }
public string PurchaseBillNo { get; set; }
public DateTime PurchaseDate { get; set; }
public decimal OtherExpenses { get; set; }
public decimal TotalBillAmount { get; set; }
public ObservableListSource<PurchaseItem> PurchaseItems { get; set; }
}
public class PurchaseItem
{
public PurchaseItem()
{
}
public int ID { get; set; }
[Required]
public virtual Purchase Purchase { get; set; }
[Required]
public virtual Product Product { get; set; }
public decimal PurchasePrice { get; set; }
public decimal Quantity { get; set; }
public decimal Amount { get; set; }
}
答案 0 :(得分:1)
在Purchase
模型中,您应该通过分配PurchaseItems
来初始化构造函数中的new ObservableListSource<PurchaseItem>()
属性:
public class Purchase
{
public Purchase()
{
PurchaseItems = new ObservableListSource<PurchaseItem>();
}
public int ID { get; set; }
public string PurchaseBillNo { get; set; }
public DateTime PurchaseDate { get; set; }
public decimal OtherExpenses { get; set; }
public decimal TotalBillAmount { get; set; }
public ObservableListSource<PurchaseItem> PurchaseItems { get; set; }
}