1
votes

With ef6 created a master detail Winforms using bindingnavigator and bindingsource.

I am able to retrieve and update or add child rows to the existing, but when i add new master and child records from the screen it updates only master. child records go disappear. Also noticed that child records vanish when I change any master details.

If I go and add one child row from back-end , then i am able to edit and add new child rows from the screen.

I think the issue could be due to a missing foreign key for new records, will Entity Framework handover the master key to details as foreign key or is there any values to be set?

Code of loading data and data-binding:

//
_context.Purchases.Include("PurchaseItems").Load();
purchaseBindingSource.DataSource = _context.Purchases.Local.ToBindingList();

//
purchaseItemsBindingSource.DataMember = "PurchaseItems";
purchaseItemsBindingSource.DataSource = this.purchaseBindingSource;

Models:

//
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; }
}
1
It depends on code and data bindings settings. You should post models codes and how you load data and how you bind datagridviews and bindingsources. - Reza Aghaei
updated with code details - user3658516
Add code of Purchase too. - Reza Aghaei
Purchase and PurchaseItems models updated - user3658516

1 Answers

1
votes

In your Purchase model, you should initialize PurchaseItems property in constructor by assigning 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; }
}