Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: An error occurred while updating the entries

I know there's a lot of questions about it but i've read like 20 of them and couldn't find answer for me. I have this error

"An exception of type 'System.Data.Entity.Infrastructure.DbUpdateException' occurred in EntityFramework.dll but was not handled in user code

Additional information: An error occurred while updating the entries. See the inner exception for details."

When I go to InnerException it says

"Invalid object name 'dbo.Samochodies'."

. I don't know what the hell is this because i don't have any 'Samochodies' in my program.. Anyway, that's the code:

CarsController.cs

public ActionResult Create([Bind(Include = "Id,Brand,Model,Price,Bought,Sold")] Samochody car)
    {
        if (ModelState.IsValid)
        {
            baza.Cars.Add(car);
            baza.SaveChanges(); //error here
            return RedirectToAction("Index");
        }
        return View(car);
    }

Samochody class

public class Samochody
{
    public int Id { get; set; }
    public string Brand { get; set; }
    public string Model { get; set; }
    public decimal Price { get; set; }
    public DateTime Bought { get; set; }
    public DateTime Sold { get; set; }

    public class CarDBCtxt : DbContext
    {
        public DbSet<Samochody> Cars { get; set; }
    }
like image 246
Szymon Kądziołka Avatar asked Dec 20 '25 00:12

Szymon Kądziołka


2 Answers

When you work with an existing DB, if you don't specify the table name with you're mapping your entity, then EF will try to find by convention a table named Samochodies in your DB. One solution could be using Table attribute to specify the real table name:

[Table("YourTableName")]
public class Samochody
{
  //...
}

Now, maybe the exception is because you changed the name of your entity. To case like this EF has some initializers that could help you to solve this kind of issue every time you change the model, in your case it would be:

public class CarDBCtxt : DbContext
{
    public DbSet<Samochody> Cars { get; set; }

    public CarDBCtx(): base("CarDBCtxt") 
    {
      Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CarDBCtxt>());  
    }
}

If you want to learn more about initializers, take a look this link.

like image 74
octavioccl Avatar answered Dec 21 '25 12:12

octavioccl


problem was that the Id of the table is not AUTO_INCREMENT,please make Id as AUTO_INCREMENT

like image 35
Amjad shaha Avatar answered Dec 21 '25 13:12

Amjad shaha