none
Entity Framework - Adding new record with child tables

    Question

  •  I have three tables CallSlip, CallSlipLabors, and CallSlipMaterials.   The Labor and Material records are both associated to the CallSlip table, where there can be multiple Labor and Material records.

    My code I am using to read the object graph for an existing CallSlip is working perfect.  I have the Labor and Material tables bound to two grids (Labor and Material).   I can modify, add, delete using the grids.  when I save it updates the database as expected.  Perfect!

    Here is my problem.   I now want the user to click an "Add" button where I can create the Object graph described above.  I create a new CallSlip (parent) and I want two empty list for the Labor and Materials.  I have tried several things with no luck.  This is my code as it today.

    context = new CallSlipContext(ConnStr);
    _CallSlip = new CallSlip();
    context.AttachTo(
    "CallSlips", _CallSlip);
    context.LoadProperty<
    CallSlip>(_CallSlip, r => r.CallSlipLabors);
    context.LoadProperty<
    CallSlip>(_CallSlip, r => r.CallSlipMaterials);
    return _CallSlip;

    The bug I get is when I try to add a piece of material using the grid.   I get the following error.  
    "Objects added to a BindingSource's list must all be of the same type"

    Any idea what I'm missing?

    Thanks
    Dan

     

     

    Thursday, September 23, 2010 2:59 PM

Answers

  • Dan,

    the following blog provides tips that you may find useful for your scenario.

    http://blogs.msdn.com/b/diego/archive/2008/10/09/quick-tips-for-entity-framework-databinding.aspx

    I created  a WinForms sample application that uses a data source based on an entity (Department) that has dependent entities (Courses).

    The sample adds new department with a new Course. And also deletes a department and all the courses. Here is the code:

      public partial class Form1 : Form
      {
        SchoolEntities context;
        IBindingList departmentsBindingList;
        public Form1()
        {
          InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
          context = new SchoolEntities();
          // Define a query that returns all Department 
          // objects and course objects, ordered by name.
          var departmentQuery = from d in context.Departments
                     orderby d.Name
                     select d;
    
          departmentsBindingList = ((IListSource)departmentQuery).GetList() as IBindingList;
          departmentBindingSource.DataSource = departmentsBindingList;
        }
    
        private void btnAddNewDptAndCourses_Click(object sender, EventArgs e)
        {
          Department newDepartment = new Department()
          {
            DepartmentID = 111,
            Budget = 13000.000m,
            Name = "New Department",
            StartDate = DateTime.Now
          };
    
          Course newCourse = new Course()
          {
            CourseID = 222,
            DepartmentID = 111,
            Title = "New Onsite Course",
            Credits = 4
          };
          newDepartment.Courses.Add(newCourse);
          // Adding an entity to the binding list
          // will result in the entity beging added to the context. 
          departmentsBindingList.Add(newDepartment);
    
        }
    
        private void btnDeleteDptAndCourses_Click(object sender, EventArgs e)
        {
          Department dpt = (Department)departmentBindingSource.Current;
          // Deleting entities from the context will result in 
          // entities being removed from all binding lists that contain them. 
          foreach (var c in dpt.Courses.ToList())
          {
            context.Courses.DeleteObject(c);
          }
          context.Departments.DeleteObject(dpt);
    
        }
    
        private void btnSave_Click(object sender, EventArgs e)
        {
          context.SaveChanges();
        }
    
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
          context.Dispose();
        }
      }

    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Marked as answer by Roahn Luo Wednesday, September 29, 2010 9:05 AM
    Friday, September 24, 2010 9:52 PM

All replies

  • Some additional information:

    I've continued to try different approaches.   This code seems to make the BindingSource happy when I attempt to add new rows.

    _CallSlip =

     

    new CallSlip();
    _CallSlip.CallSlipLabors =
    new List<TMS.Acowin.DA.CallSlip.CallSlipLabor>();
    _CallSlip.CallSlipMaterials =
    new List<TMS.Acowin.DA.CallSlip.CallSlipMaterial>();
    context.AttachTo(
    "CallSlips", _CallSlip);

    The problem that occurs now is immediately after I add the row I need to loop through each and perform calculations.  I received this error on the foreach statement:
    Collection was modified; enumeration operation may not execute.

     

    I'm not even sure I'm going down the right path here.   Any help would be appreciated.

    Thanks
    Dan

     

     

     

    Thursday, September 23, 2010 7:20 PM
  • Dan,

    the following blog provides tips that you may find useful for your scenario.

    http://blogs.msdn.com/b/diego/archive/2008/10/09/quick-tips-for-entity-framework-databinding.aspx

    I created  a WinForms sample application that uses a data source based on an entity (Department) that has dependent entities (Courses).

    The sample adds new department with a new Course. And also deletes a department and all the courses. Here is the code:

      public partial class Form1 : Form
      {
        SchoolEntities context;
        IBindingList departmentsBindingList;
        public Form1()
        {
          InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
          context = new SchoolEntities();
          // Define a query that returns all Department 
          // objects and course objects, ordered by name.
          var departmentQuery = from d in context.Departments
                     orderby d.Name
                     select d;
    
          departmentsBindingList = ((IListSource)departmentQuery).GetList() as IBindingList;
          departmentBindingSource.DataSource = departmentsBindingList;
        }
    
        private void btnAddNewDptAndCourses_Click(object sender, EventArgs e)
        {
          Department newDepartment = new Department()
          {
            DepartmentID = 111,
            Budget = 13000.000m,
            Name = "New Department",
            StartDate = DateTime.Now
          };
    
          Course newCourse = new Course()
          {
            CourseID = 222,
            DepartmentID = 111,
            Title = "New Onsite Course",
            Credits = 4
          };
          newDepartment.Courses.Add(newCourse);
          // Adding an entity to the binding list
          // will result in the entity beging added to the context. 
          departmentsBindingList.Add(newDepartment);
    
        }
    
        private void btnDeleteDptAndCourses_Click(object sender, EventArgs e)
        {
          Department dpt = (Department)departmentBindingSource.Current;
          // Deleting entities from the context will result in 
          // entities being removed from all binding lists that contain them. 
          foreach (var c in dpt.Courses.ToList())
          {
            context.Courses.DeleteObject(c);
          }
          context.Departments.DeleteObject(dpt);
    
        }
    
        private void btnSave_Click(object sender, EventArgs e)
        {
          context.SaveChanges();
        }
    
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
          context.Dispose();
        }
      }

    This posting is provided "AS IS" with no warranties, and confers no rights.
    • Marked as answer by Roahn Luo Wednesday, September 29, 2010 9:05 AM
    Friday, September 24, 2010 9:52 PM
  • I appreciate the help.    It proved to be very helpful.   I think I'm on my way now.  

    Thanks for all your help.

    Dan

     

    Thursday, September 30, 2010 1:12 PM
  • Great! Please, let us know if you have further questions.

    -Julia


    This posting is provided "AS IS" with no warranties, and confers no rights.
    Thursday, September 30, 2010 3:01 PM