正确的方式实体框架主 - 详细插入记录代码插入子

时间:2014-01-16 11:22:02

标签: c# .net entity-framework

我是Entity Framework的新手,并且想要学习更新数据的正确方法。

客户

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; }
}

联系

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 
    }

如何添加联系方式?

如何从datagridView列添加get值?

该代码是否正常,或者有人建议更好的方法。

在何处/如何从表单中删除插入代码到单独的类?

感谢。

1 个答案:

答案 0 :(得分:3)

    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();

更好的方法是在实体对象

中进行集合初始化
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;
       } 
     }
}