I'm new to Entity Framework and tying to learn correct way of updating data.
Customer
public partial class Customer
{
public Customer()
{
this.Contacts = new ObservableListSource<Contact>();
}
public int CustomerId { get; set; }
public int CustomerCustomId { get; set; }
public string CustomerName { get; set; }
public virtual ObservableListSource<Contact> Contacts { get; set; }
}
Contact
public partial class Contact
{
public int ContactId { get; set; }
public string ContactName { get; set; }
public string ContactMobile { get; set; }
public int CustomerCustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
Form1
private void Form1_Load(object sender, EventArgs e)
{
_context = new winproContext();
var query = _context.Customers;
this.customerBindingSource.DataSource = query.ToList();
}
private void customerBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
try
{
this.Validate();
_context.SaveChanges();
MessageBox.Show("Data saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void bindingNavigatorAddNewItem_Click(object sender, EventArgs e)
{
var customer = new Customer { CustomerName = "test" };
_context.Customers.Add(customer);
_context.SaveChanges();
// How to add contact details ?
// How to add get value from datagridView column
}
How to add contact details ?
How to add get value from datagridView column ?
Is that code ok or can someone suggest better way of doing this.
Where/how to remove insert code from forms into separate class?
Thanks.
var customer = new Customer { CustomerName = "test" };
_context.Customers.Add(customer);
var newContact = new Contact();
customer.Contacts = new ObservableListSource<Contact>();// it needs becorse your collection is null
customer.Contacts.Add(newContact); //just add new child to collection of parent
_context.Customers.Add(customer);
_context.SaveChanges();
the better way is to make collection initialization inside of entity object
public partial class Customer
{
public Customer()
{
this.Contacts = new ObservableListSource<Contact>();
}
public int CustomerId { get; set; }
public int CustomerCustomId { get; set; }
public string CustomerName { get; set; }
protected ObservableListSource<Contact> _Contacts;
public virtual ObservableListSource<Contact> Contacts
{
get{
if( _Contacts==null) _Contacts= new ObservableListSource<Contact>();
return _Contacts;
}
set{
_Contacts=value;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句