dmikester1
dmikester1

Reputation: 1382

Entity Framework - Error on db.SaveChanges()

I am using the Entity Framework to create a database and write to it from my model and controller. I am getting an error on the line "DB.SaveChanges();". The error states: "An error occurred while updating the entries. See the inner exception for details." Then the inner exceptions states: "Invalid object name 'dbo.ContactModel'." I have looked through all the SO posts with a similar question but none seemed to fix my issue. I will post the code that I think is relevant to the issue. Let me know if there is more needed.

My ContactContext.cs class:

using newBestPlay.Models;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace newBestPlay.DAL
{
    public class ContactContext : DbContext
    {

        public ContactContext() : base("BestPlay")
        {
        }

        public DbSet<ContactModel> Contacts { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}

And my < connectionStrings > in web.config:

<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDBFilename=|DataDirectory|\Contacts.mdf;Initial Catalog=Contacts;Integrated Security=True" providerName="System.Data.SqlClient" />
<add name="BestPlay" connectionString="Data Source=(LocalDb)\v11.0;Integrated Security=True" providerName="System.Data.SqlClient" />    
< /connectionStrings >

Here is the index post method in the controller:

// POST: Contact/Index
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "ID,name,address,city,state,zip,phone,fax,email,requestType,emailAlerts,message")] ContactModel contactModel)
{
    if (ModelState.IsValid)
    {
        contactModel.name = ToTitleCase(contactModel.name);
        contactModel.address = ToTitleCase(contactModel.address);
        contactModel.city = ToTitleCase(contactModel.city);
        db.Contacts.Add(contactModel);
        db.SaveChanges();
        TempData["Message"] = "Thank you for your input.  If requested, we will contact you soon.";
        return RedirectToAction("Index");
    }

    return View(contactModel);
}

I would think that would be all that is needed. Let me know if more code is needed.

Upvotes: 2

Views: 22168

Answers (2)

dmikester1
dmikester1

Reputation: 1382

So I finally figured it out with some help narrowing it down from Yuval Itzchakov. My table did not exist and I thought the Entity Framework was supposed to automatically create it for me. Well it wasn't. The actual query that was failing was this: INSERT [dbo].[Contacts]([name], [address], [city], [state], [zip], [phone], [fax], [email], [requestType], [emailAlerts], [message]) VALUES (@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10) SELECT [ID] FROM [dbo].[Contacts] WHERE @@ROWCOUNT > 0 AND [ID] = scope_identity()

So it was trying to run a select on a non-existant table. I figured out that I had to add this line into my ContactContext class in the constructor:

Database.SetInitializer<ContactContext>(new CreateDatabaseIfNotExists<ContactContext>());

That did the trick!

Upvotes: 2

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149628

If you're overriding OnModelCreating, you need to pass the mapping to your DbModelBuilder, as the entity name and the table in your database don't match:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    modelBuilder.Entity<ContactModel>().ToTable("Contacts");
}

Upvotes: 1

Related Questions