none
Performing CRUD Operation Like Delete on Anonymous Type RRS feed

  • Question

  • Hello,

    Please, with regards the anonymous object, I am a little bit lost trying to perform a CRUD operation on it. Since a datagridview is bind to the anonymous object class, how then can I perform a CRUD operation on it. Initially, I added a property called ID on the DTo class, I could get the id successfully, but when I get to tell the database what table to perform operation on, I need to specify the table name and the DTo class was manually created, so I can’t use that.

    Take for example, I need to perform a delete operation on a row selected by the user. I have written this code so far, but the challenge is how to go about delete records on the DTo that will affect the actual table on the database.

    So far, I did a little research and found similar question (https://social.msdn.microsoft.com/Forums/en-US/1bc3c15d-c102-44a4-ac03-6a96815544b6/how-to-perform-update-and-delete-operations-with-dto?forum=adodotnetentityframework) have been asked, but when I tried same, it doesn’t work for me because it wasn't clear which table the person specified and how the id was gotten.

    Here is what I have so far on code

      private void Delete(PatientCartDto temp)
            {
                if (dataGridViewCart.CurrentRow.Index != -1)
                {
                    temp.Id = Convert.ToInt32(dataGridViewCart.CurrentRow.Cells["Id"].Value);
    
                    var entity = this.dbHelper.temp_service.FirstOrDefault(row => row.temp_service_id == temp.Id);
                    if (MessageBox.Show($"Are you sure you want to delete from the Cart?", "Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        
                        using (Model db = new Model())
                        {
                            var result = db.Entry(temp);
                            if (result.State == EntityState.Detached)
                                db.temp_service.Attach(???);
                            db.temp_service.Remove(???);
                            db.SaveChanges();
                            MessageBox.Show("Record Deleted Successfully", "Message");
                        }
                       
                    }
                }
            }

    Any idea is well appreciated on what actual object to pass.

    Friday, October 26, 2018 12:20 AM

Answers

  • Hi Godymn,

    Please try the following code.

    private void Update(casenote casenote)
            {
                using (MyTestEntities db = new MyTestEntities())
                {
                    var casnote = db.casenotes.Find(_editHelper.casenote_id);
    
                    casnote.creator_id = Convert.ToInt32(textBox1.Text);
                    casnote.category_id = Convert.ToInt32(textBox2.Text);
                    casnote.patient_id = Convert.ToInt32(textBox3.Text);
    
                    //_editHelper.creator_id = Convert.ToInt32(textBox1.Text);
                    //_editHelper.category_id = Convert.ToInt32(textBox2.Text);
                    //_editHelper.patient_id = Convert.ToInt32(textBox3.Text);
                    
                   // db.Entry(casenote).State = EntityState.Modified;
                    db.SaveChanges();
                    MessageBox.Show("Updated Successfully!", "Message");
                    Close();
                }
            }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Godymn Wednesday, October 31, 2018 8:57 AM
    Wednesday, October 31, 2018 8:13 AM
    Moderator

All replies

  • Hi Godymn,

    Please find related entity from database and then remove it. like this:

    private void Delete(PatientCartDto temp)
            {
                if (dataGridViewCart.CurrentRow.Index != -1)
                {
                    temp.Id = Convert.ToInt32(dataGridViewCart.CurrentRow.Cells["Id"].Value);
    
                    //var entity = this.dbHelper.temp_service.FirstOrDefault(row => row.temp_service_id == temp.Id);
                    if (MessageBox.Show($"Are you sure you want to delete from the Cart?", "Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        
                        using (Model db = new Model())
                        {
                            var deleteServ = db.temp_service.find(temp.id);           
                            db.temp_service.Remove(deleteServ);
                            db.SaveChanges();
                            MessageBox.Show("Record Deleted Successfully", "Message");
                        }
                       
                    }
                }
            }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Friday, October 26, 2018 1:23 AM
    Moderator
  • Hi Godymn,

    Please find related entity from database and then remove it. like this:

    private void Delete(PatientCartDto temp)
            {
                if (dataGridViewCart.CurrentRow.Index != -1)
                {
                    temp.Id = Convert.ToInt32(dataGridViewCart.CurrentRow.Cells["Id"].Value);
    
                    //var entity = this.dbHelper.temp_service.FirstOrDefault(row => row.temp_service_id == temp.Id);
                    if (MessageBox.Show($"Are you sure you want to delete from the Cart?", "Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        
                        using (Model db = new Model())
                        {
                            var deleteServ = db.temp_service.find(temp.id);           
                            db.temp_service.Remove(deleteServ);
                            db.SaveChanges();
                            MessageBox.Show("Record Deleted Successfully", "Message");
                        }
                       
                    }
                }
            }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Hi Zhanglong,

    Thanks for the response and sorry I am just getting back to you. Been away for a while.

    I modified my code based on your suggestion today and luckily, it worked just fine.

    But still on this anonymous object type, just to conclude, I tried using this same approach to carry out an update but doesn’t work. Throws and exception error that reads:

    “An entity object cannot be referenced by multiple instances of IEntityChangeTracker.”

    I checked my code and I just have one instance of _editItemFromCart. I even made it readonly to avoid a situation of me mistakenly creating another object…

    Here is where I am calling a form and passing the temp_service

     private temp_service EditItemFromCart(PatientCartDto temp)
            {   
                if (dataGridViewCart.CurrentRow.Index != -1)
                {
                    temp.Id = Convert.ToInt32(dataGridViewCart.CurrentRow.Cells["Id"].Value);       
                }
                return dbHelper.temp_service.Find(temp.Id);
            }
    
    
     private void btnEdit_Click(object sender, EventArgs e)
            {
                var result = EditItemFromCart(new PatientCartDto());
                if (result == null)
                    MessageBox.Show("Something went wrong", "Error");
                else
                {
                    ServiceCart sc = new ServiceCart(result);
                    sc.Text = "Edit Service";
                    sc.ShowDialog();
                }
            }

    And here is a new class for ServiceCart where i am using the data passed to populate and also carry out an update.

    private readonly temp_service _editItemFromCart;
    
      public ServiceCart(temp_service editItemFromCart)
            {
                InitializeComponent();
                _editItemFromCart = editItemFromCart;
            }
    
    private void btnEdit_Click(object sender, EventArgs e)
            {
    var result = InitServicePreview();
                using (Model db = new Model())
                    {
                        _editItemFromCart.user_id = _loggedInUser.user_id;
                        _editItemFromCart.service_id = result.service_id;
                        _editItemFromCart.price = result.price;
                        db.Entry(_editItemFromCart).State = EntityState.Modified;
                        db.SaveChanges();
                        MessageBox.Show("Service Updated Successfully!", "Message");
                        Close();
                    }
            }

    I have highlighted a line bold which seems to be where the error is coming from.

    Any idea what i am not doing right this time?


    Tuesday, October 30, 2018 3:01 AM
  • Hi Godymn,

    Please find related entity from database and then remove it. like this:

    private void Delete(PatientCartDto temp)
            {
                if (dataGridViewCart.CurrentRow.Index != -1)
                {
                    temp.Id = Convert.ToInt32(dataGridViewCart.CurrentRow.Cells["Id"].Value);
    
                    //var entity = this.dbHelper.temp_service.FirstOrDefault(row => row.temp_service_id == temp.Id);
                    if (MessageBox.Show($"Are you sure you want to delete from the Cart?", "Delete User", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        
                        using (Model db = new Model())
                        {
                            var deleteServ = db.temp_service.find(temp.id);           
                            db.temp_service.Remove(deleteServ);
                            db.SaveChanges();
                            MessageBox.Show("Record Deleted Successfully", "Message");
                        }
                       
                    }
                }
            }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Hi Zhanglong,

    Thanks for the response and sorry I am just getting back to you. Been away for a while.

    I modified my code based on your suggestion today and luckily, it worked just fine.

    But still on this anonymous object type, just to conclude, I tried using this same approach to carry out an update but doesn’t work. Throws and exception error that reads:

    “An entity object cannot be referenced by multiple instances of IEntityChangeTracker.”

    I checked my code and I just have one instance of _editItemFromCart. I even made it readonly to avoid a situation of me mistakenly creating another object…

    Here is where I am calling a form and passing the temp_service

     private temp_service EditItemFromCart(PatientCartDto temp)
            {   
                if (dataGridViewCart.CurrentRow.Index != -1)
                {
                    temp.Id = Convert.ToInt32(dataGridViewCart.CurrentRow.Cells["Id"].Value);       
                }
                return dbHelper.temp_service.Find(temp.Id);
            }
    
    
     private void btnEdit_Click(object sender, EventArgs e)
            {
                var result = EditItemFromCart(new PatientCartDto());
                if (result == null)
                    MessageBox.Show("Something went wrong", "Error");
                else
                {
                    ServiceCart sc = new ServiceCart(result);
                    sc.Text = "Edit Service";
                    sc.ShowDialog();
                }
            }

    And here is a new class for ServiceCart where i am using the data passed to populate and also carry out an update.

    private readonly temp_service _editItemFromCart;
    
      public ServiceCart(temp_service editItemFromCart)
            {
                InitializeComponent();
                _editItemFromCart = editItemFromCart;
            }
    
    private void btnEdit_Click(object sender, EventArgs e)
            {
    var result = InitServicePreview();
                using (Model db = new Model())
                    {
                        _editItemFromCart.user_id = _loggedInUser.user_id;
                        _editItemFromCart.service_id = result.service_id;
                        _editItemFromCart.price = result.price;
                        db.Entry(_editItemFromCart).State = EntityState.Modified;
                        db.SaveChanges();
                        MessageBox.Show("Service Updated Successfully!", "Message");
                        Close();
                    }
            }

    I have highlighted a line bold which seems to be where the error is coming from.

    Any idea what i am not doing right this time?


    Please, anyone with an idea on how to go about the update operation on anonymous type?
    Wednesday, October 31, 2018 4:11 AM
  • Hi Godymn,

    Is the variable named _editItemFromCart a entity framework entity object, or a DTO object. could you please share a simple complete to reproduce the issue.

    Best regards,

    Zhanglong 


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, October 31, 2018 5:11 AM
    Moderator
  • Hi Godymn,

    Is the variable named _editItemFromCart a entity framework entity object, or a DTO object. could you please share a simple complete to reproduce the issue.

    Best regards,

    Zhanglong 


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Hi Zhanglong,

    I have made amendment on the sample project i shared before to reproduce this.

    I didn't touch the database. So, when trying to edit a casenote entry, try to change the createdBy id to any valid user id on your database. Then, you get the error.

    Here is the link to the sample project

    https://1drv.ms/f/s!Aq-hLZmB9gUFh9FfdMyemqL9SoebuQ

    Thanks for your help and time.

    Wednesday, October 31, 2018 7:31 AM
  • Hi Godymn,

    Please try the following code.

    private void Update(casenote casenote)
            {
                using (MyTestEntities db = new MyTestEntities())
                {
                    var casnote = db.casenotes.Find(_editHelper.casenote_id);
    
                    casnote.creator_id = Convert.ToInt32(textBox1.Text);
                    casnote.category_id = Convert.ToInt32(textBox2.Text);
                    casnote.patient_id = Convert.ToInt32(textBox3.Text);
    
                    //_editHelper.creator_id = Convert.ToInt32(textBox1.Text);
                    //_editHelper.category_id = Convert.ToInt32(textBox2.Text);
                    //_editHelper.patient_id = Convert.ToInt32(textBox3.Text);
                    
                   // db.Entry(casenote).State = EntityState.Modified;
                    db.SaveChanges();
                    MessageBox.Show("Updated Successfully!", "Message");
                    Close();
                }
            }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by Godymn Wednesday, October 31, 2018 8:57 AM
    Wednesday, October 31, 2018 8:13 AM
    Moderator
  • Hi Godymn,

    Please try the following code.

    private void Update(casenote casenote)
            {
                using (MyTestEntities db = new MyTestEntities())
                {
                    var casnote = db.casenotes.Find(_editHelper.casenote_id);
    
                    casnote.creator_id = Convert.ToInt32(textBox1.Text);
                    casnote.category_id = Convert.ToInt32(textBox2.Text);
                    casnote.patient_id = Convert.ToInt32(textBox3.Text);
    
                    //_editHelper.creator_id = Convert.ToInt32(textBox1.Text);
                    //_editHelper.category_id = Convert.ToInt32(textBox2.Text);
                    //_editHelper.patient_id = Convert.ToInt32(textBox3.Text);
                    
                   // db.Entry(casenote).State = EntityState.Modified;
                    db.SaveChanges();
                    MessageBox.Show("Updated Successfully!", "Message");
                    Close();
                }
            }

    Best regards,

    Zhanglong


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Hi Zhanglong,

    This works just fine. Thank you.

    Please, just for proper clarification and understanding, can you explain why i have to search for an entity twice?.

    I thought, when selecting a row from the gridview in the patientDashboard class and passing it to updateform constructor, the id never changes since i also made it read-only to avoid me mistakenly creating an object.

    Why do i have to find an entity in the patientDashboard and also in the updateform couple with the fact that i am trying to reduce the number of times i access my db??

    Appreciate your feedback.

    Wednesday, October 31, 2018 8:51 AM