logo
down
shadow

Entity Framework inserting new rows instead of updating them


Entity Framework inserting new rows instead of updating them

By : user2954606
Date : November 22 2020, 10:31 AM
this will help I have a problem when I am updating data to database. When I want to update data, Entitiy Framework adds new rows to tables that can have multiple rows (tables that have foreign key). , Update properties rather than set new objects.
code :
  Updatecontact.Emails1.email1 = contact.Emails1.email1;
  Updatecontact.Phones1.number = contact.Phones1.number;
  Updatecontact.Tags1.tag1 = contact.Tags1.tag1;
 foreach ( var email in contact.Emails1 )
 {
     // first make sure the object is retrieved from the database 
     var updateemail = Updatecontact.Emails1.FirstOrDefault( e => e.id == email.id );
     // then update its properties
     updateemail.email1 = email.email1;
 }

 // do the same for phones and tags


Share : facebook icon twitter icon
entity framework inserting a many-to-many relationship between two existing objects while updating

entity framework inserting a many-to-many relationship between two existing objects while updating


By : user1832824
Date : March 29 2020, 07:55 AM
I wish this helpful for you It doesn't look to me like your User object is detached, so you shouldn't need to call ApplyPropertyChanges().
General persist method in Entity Framework - inserting or updating (if exists) entity

General persist method in Entity Framework - inserting or updating (if exists) entity


By : alo malo
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , In your example where you can't recognize if a Company instance is new or has been formerly loaded from the database you must query the DB:
code :
public void Persist(Company company)
{
    var companyInDb = _dbSet.SingleOrDefault(c => c.Id == company.Id);
    if (companyInDb != null)
    {
        _context.Entry(companyInDb).CurrentValues.SetValues(company);
    }
    else
    {
        _dbSet.Add(company);
    }
    _context.SaveChanges();
}
public class Company
{
    public Company()
    {
    }

    public Company(bool isNew)
    {
        Id = Guid.NewGuid();
        _isNew = isNew;
    }

    public Guid Id { get; set; }
    public string Name { get; set; }

    private bool _isNew;
    public IsNew { get { return _isNew; } }
}
public void Persist(Company company)
{
    if (!company.IsNew)
    {
        _context.Entry(company).State = EntityState.Modified;
    }
    else
    {
        _dbSet.Add(company);
    }
    _context.SaveChanges();
}
Entity Framework Many-to-Many Inserting Fine, But Not Properly Updating

Entity Framework Many-to-Many Inserting Fine, But Not Properly Updating


By : shravan
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I think that you must update the employee it self after editing the skills as below
code :
private void UpdateSkills(Employee employee, IEnumerable<int> updatedSkills)
{
    if (employee.Skills != null)
    {
        var updatedSkillsList = updatedSkills as IList<int> ?? updatedSkills.ToList();
        var addedSkills = updatedSkillsList.Except(employee.Skills.Select(x => x.Id));
        var removedSkills = employee.Skills.Select(x => x.Id).Except(updatedSkillsList);

        addedSkills.ForEach(x => employee.Skills.Add(_skillService.GetById(x)));
        removedSkills.ForEach(x => employee.Skills.Remove(_skillService.GetById(x)));

         // here 
         _employeeService.Update(employee);
    }
    else
    {
        employee.Skills = new List<Skill>();
        newSkills.ForEach(x => employee.Skills.Add(_skillService.GetById(x)));
    }
}
public ActionResult Edit(int id, EmployeeEditViewModel viewModel)
{
   try
   {
    if (!ModelState.IsValid)
    {
        viewModel.SkillsList = _skillService.GetAll().ToList();
        return View(viewModel);
    }

    //here your mapper is not attaching the employee to the context
    //var employee = Mapper.Map<Employee>(viewModel);

    you can do this 
    var employee = _employeeService.GetById(viewModel.Id);
    // after that ... update what the user did from the view model except the id as the id won't change
    employee = Mapper.Map<Employee>(viewModel, employee);
    // I think that the mapping have another overload to map to a destination. you can set the setup for the mappnig in the startup to ignore updating Ids        

    UpdateSkills(viewModel.NewSkills);

    _employeeService.Update(employee);

    return RedirectToAction("Index");
}
catch(Exception e)
{
    ModelState.AddModelError("", e.Message);
    viewModel.SkillsList = _skillService.GetAll().ToList();
    return View(viewModel);
}
Getting an error when inserting multiple rows via Entity Framework 7

Getting an error when inserting multiple rows via Entity Framework 7


By : Pierre
Date : March 29 2020, 07:55 AM
wish help you to fix your issue SQL Server 2005 is not supported by Entity Framework 7 (in fact SQL Server 2005 is not supported by Microsoft any longer).
Specifically, the multi-row INSERT VALUES syntax used by EF7 is not supported, it requires SQL Server 2008 or newer.
Entity Framework 4 InvalidOperationException While Inserting or Updating

Entity Framework 4 InvalidOperationException While Inserting or Updating


By : user4043423
Date : March 29 2020, 07:55 AM
will be helpful for those in need I think that the problem is with the Navigation Properties. I will try to give a short example.
Let's say that you have two entities Order and Customer. If you fetch the Customer and keep it in memory then add it to an instance of a Order object ex. Order.Customer= Customer then the automatic fixup of NavigationProperties is going to add the order to the Navigation properties of the Customer.
Related Posts Related Posts :
  • Marshal.Copy attempted to read or write protected memory At Random Times
  • Restrict Type variable to specific class or subclass
  • Horizontal text alignment in a PdfPCell
  • C# crashing with Form.show() command, ObjectDisposedException - Deeper look / explanation please
  • Will the result of a LINQ query always be guaranteed to be in the correct order?
  • "Could not find default endpoint element that references contract"
  • Umbraco Request.QueryString is null if it's the first time the page is loaded
  • Error inconsistent accessibility method C#
  • How to program Intel Xeon Phi with C#?
  • remove nested element using regular expression
  • Is there a C# alternative to Java's vararg parameters?
  • Clear particular column values in DataTable
  • how to add event handler to programatically created checkboxes
  • Cannot apply indexing with [] to an expression of type 'System.Collections.Specialized.NameValueCollection'
  • Check for key in pre-existing dictionary in case insensitive manner
  • How to remove year from datetime object?
  • Accessing Settings in different ways
  • "This project is empty" error in Sonarqube
  • How to create reusable icon menu in Xamarin
  • Value Cannot be null in Ado.Net connectivity
  • Adding a custom/dynamic attribute when using XSD.exe
  • How to convert object to correct type
  • Automatically sign out from Forms Authentication in ASP.NET when browser is closed
  • Can a WCF service support both Buffered and Streamed transfer modes?
  • Verify a CA Certificate with a public key in C#
  • How to invoke a Web Service that requires the "patch" verb using the C# WebClient wrapper?
  • Proper way a implementing property based on generic type
  • Closing a form that is created in another thread
  • How Can You Bind a List<String> to a StackPanel
  • WPF Application Update Best Practices - Architectural Explanation
  • System.UnauthorizedAccessException in Server.MapPath()
  • Connecting and Using SQL Compact Edition in a WPF application
  • C#: weird ref in constructor to behave like "virtual field"
  • C# XDocument Load with multiple roots
  • How to decide what goes in the Domain or Application Project in a "DDD" solution?
  • How to get/set a property of an interface that is not always implemented
  • Read-only array field in unsafe struct
  • i got "Invalid attempt to call Read when reader is closed" when using sqldatareader how to solve it in a three
  • Why should I encapsulate objects in using if there is garbage collection
  • How to load Word document from byte array
  • Caliburn.Micro and ContextMenu for DataGrid Row
  • Linq "join" with a IList<T> getting "Error Unable to create a constant value.."
  • How to draw red wavy line under words in RichTextBox c# winform
  • HttpPostedFileBase returns Null MVC3
  • Refresh Dropdownlist in webform
  • How to convert serialized byte array back to its text form
  • How to do a loop to check all the variables at the same time for C#?
  • Facebook Sentiment Analysis API
  • Counting occurrences of specific letters in string
  • Module 'System.Data.Linq' Version=4.0.0.0, Culture=neutral, Publickeytoken=b77a5c561934e089' should be referenced
  • C# MVC Dynamically create view model
  • Get Executing Path of C# application when using nunit with Jenkins
  • GDI count stable near 100 but Handle count keep increasing
  • Problem adding string value to ViewBag from an MVC Action using TempData
  • Reading Excel file on condition
  • what is windows programming from C++, C# and Java perspective?
  • How to deal with C# object references in MongoDB?
  • How to create a list from filtering 2 lists with linq to object
  • Webclient calls to DownloadString cause my app to freeze
  • How to create a JSON WebService in c# ASP.Net with a valid JSON output and query with JQuery/Ajax
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org