I'm developing a Windows Form app with Entity Framework.
This is a layered application which has a common layer for the db handling.
I have written a SaveSOHeader
method to save Sales Order Headers which has an issue:
It doesn't save SalesOrderHeader
records to the database table or makes duplicate records in foreign key tables.
I populate all the properties values in the Form code just before saving. This is my model classes:
public class SalesOrderHeader
{
public int Id { get; set; }
public System.DateTime OrderDate { get; set; }
public virtual Customer Customer { get; set; }
public virtual SalesPerson SalesPerson { get; set; }
// Other properties stripped to keep it simple
}
public class Customer
{
public int Id { get; set; }
public string CustName { get; set; }
public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; }
// Other properties stripped to keep it simple
}
public class SalesPerson
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<SalesOrderHeader> SalesOrderHeaders { get; set; }
// Other properties stripped to keep it simple
}
To populate the properties only for sales order header I used this code:
private SalesOrderHeader GetUIData()
{
SalesOrderHeader _soheader = new SalesOrderHeader();
try
{
_soheader.OrderDate = dtOrderDate.Value;
_soheader.Customer = new Customer() { CustName = cmbCustomerName.Text};
_soheader.SalesPerson = _SalesPersonMgr.LoadByName(cmbSalesPerson.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
return _soheader;
}
The question is this:
The following code does not save SalesOrderHeader record when I use Attach
method, and when I changed it to db.SalesOrderHeaders.Add(SO);
, records save with duplicates to customer, sales person tables etc, so it looks like db.SalesOrderHeaders.Add is an invalid solution.
I Need some expert advice to resolve this issue.
public void SaveSOHeader(SalesOrderHeader SO)
{
try
{
using (SODBContext db = new SODBContext())
{
db.SalesOrderHeaders.Attach(SO); // → Doesn't save
//db.SalesOrderHeaders.Add(SO); // → Saves but duplicates foreign key entities
db.SaveChanges();
}
}
catch (Exception ex)
{
throw ex;
}
}