SqlException (0x80131904): Invalid object name 'dbo.Categories' - c#

I am getting the exception above when I run an application. The application is using asp.net mvc 3 / C#. I made an mdf file and added it under App_Data folder in Visual Web Developer Express. I added connection strings to the web.config folder but when I run and browse to /store, I get the error above with the line var categories = storeDB.Categories.ToList(); highlighted. My database contains 6 tables and one of them is Category.
Controller:
EventCalendarEntities storeDB = new EventCalendarEntities();
public ActionResult Index()
{
var categories = storeDB.Category.ToList();
return View(categories);
}
Connection strings in web.config file:
<connectionStrings>
<add name="EventCalendarEntities"
connectionString="data source=.\SQLEXPRESS;
Integrated Security=SSPI;
AttachDBFilename=|DataDirectory|\MvcEventCalendar.mdf;
User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>

This usually means a simple configuration issue:
perhaps there genuinely is no such table
perhaps the table is there, but there is no dbo scheme (it might be in Fred.Categories)
perhaps the db is case-sensitive (which is fine), and the table is actually dbo.CATEGORIES
Any of these will cause the above exception. In particular, you state:
My database contains 6 tables and one of them is Category.
Now to a machine, Category != Categories

Try using model builder class. It is the way to configure or explicitly define the mapping between table and model class.
In your entity/context class try adding this code
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Category>().ToTable("Category");
}
It's a method. Make sure you are using all the including statements.

Since this was still top search hit on the exception in April of 2018 and it led me to a solution, let me tack this on for a specific situation...
Our application is based on ABP and ABP.Zero, and we already have a pattern that fit Marc's answer. While I bet explicit mapping in the OnModelCreating method (a la Dhananjay's answer) would have worked perfectly, it seemed like ABP's mapping was working perfectly up to this point and I didn't want to break the pattern.
My solution was to add a table attribute to the entity class, and this settled EF's confusion.
using System;
using Abp.Domain.Entities;
using System.ComponentModel.DataAnnotations.Schema;
namespace Discovery.History
{
[Table("HistoryRecords")]
public class HistoryRecord : Entity<int>
{
public int ResearcherCount { get; set; }
public DateTime DateSubmitted { get; set; }
public string Comments { get; set; }
}
}

What you really want to do to fix this is in you Context class you should have a method called OnModelCreating... make sure it has this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

Proven,tested & verified for table with name category or any SQL keywords named table use ToTable to instruct specific table name
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<category>().ToTable("category");
}

If you have a Class for mapping properties and keys without this.Map.(a table in db necessary to mapping), EntityFramework expect you have one table named like Category but convert in plural, so "Categories".. To resolve you can add this.Map(in correct table existing in your DB).

in your DbContext where you create DbSet change Categories to Category
I resolved same issue by this way

Related

HowTo Connect EF6 to MsSQL with existing MySQL Data Model

I have an existing data model Created from a existing MySQL Database. Is it possible to use this model but connect to a identical MsSQL Database?
If I change the connection string and use the metadata from MySql it complains that it can not convert the SqlConnection to a MySqlConnection (of course).
How is this properly done? Is it possible at all?
I think Miguel led me to a solution:
Solution 1
In my case I had a separate project in my solution which keeps the data model. In that project I added another ADO.NET Entity Data Model generated from the MS SQL DB. At this point it would already work, besides that we would have to change the code wherever we create or access the context. To solve this I've created a interface for the context object that the EF Wizard generated, and implemented it in a partial type. This way I can "Update the Model from Database" without loosing it:
public partial class EntitiesMs : DbContext
{
public EntitiesMs()
: base("name=EntitiesMs")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
// Your DbSet<...> Stuff
}
public partial class Entities : DbContext
{
public Entities()
: base("name=Entities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
// Your DbSet<...> Stuff
}
And in separate files of course:
public partial class Entities : IDbEntities
{
}
public partial class EntitiesMs : IDbEntities
{
}
A Factory could then return the desired object. Although this has some downsides:
If a new table is created in the DB the interface has to be modified
You would have to cast the object from the factory to access
methods like SaveChanges() (methods from the base type)
And maybe some others I have overlooked.
Solution 2
Another "quick and dirty" way I've found is to add another project to the solution and add the MS Data Model there. Make sure that the Model has the exact same name as the one for MySQL. Then the only things you have to do in your startup project is, switch the reference to the other project and switch the connection strings.
The only problem that you need to solve if the EDMX file. You may need to have one to the MySQL and one distinct to the MSSQL and specify which one you want at the connection string level.
An EF data model connection string looks like this:
<add name="Entities" connectionString="metadata=res://*/CMBS.csdl|res://*/CMBS.ssdl|res://*/CMBS.msl;provider=System.Data.SqlClient;provider connection string="data source={database};initial catalog=;persist security info=True;user id=;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
You need to update the metadata part of the connection string. Here you can find more information to manipulate EDMX files.
Hope this help!

Entity Framework renaming mistake

I am using Entity Framework Code First in my project, and I did something quite silly I can't fix. I have renamed a table in SQL Server Management Studio, and then deleted it there. I then recreated the correct table (just an 's' that wasn't supposed to be here). Now it's not here anymore and I keep getting exceptions in my queries since EF looks for a table that does not exist anymore (even though I renamed it everywhere!). Now my table is called RelImpUser and it used to be RelImpUsers.
So I have tried recreating the table in SQL Server, then making a migration with :
public override void Down()
{
DropTable("dbo.RelImpUsers");
}
But this does not delete my table. And everytime I execute a query, it looks in RelImpUsers, it does not go for RelImpUser which is the only name I put in my code. Any ideas how to fix this? I can add some code if you want, I just felt it doesn't help much here.
Edit 1: It might have to do with the pluralization of my tables. So all my tables all had plural names, but the new one doesn't, BUT EF still pluralizes because I checked the option when creating DB Code First.
Thanks!
Code First uses its models to build the queries. You will need to annotate your RelImpUser class (or add comparable fluent code):
using System.ComponentModel.DataAnnotations.Schema;
[Table("RelImpUser")]
public class RelImpUser
{
public int RelImpID { get; set; }
public string Field1{ get; set; }
...
}
Fluent equivalent:
modelBuilder.Entity<RelImpUser>().ToTable("RelImpUser");
If you don't want pluralized names, you can turn that convention off:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}

Merge MyDbContext to Asp.net IdentityDbContext

I saw a lot of examples online but none that I could use from top to bottom about merging my own DbContext with Asp.net IdentityDbContext.
Can someone please walk me through it? I am at step 0, and what I want is to have the tables generated by ASP.net IdentityDbContext inside my own database, so that I can retain user data in my own database. How can I achieve that?
Thanx in advance :)
If I got you correct, you are trying to use your existing database, tables and existing users with asp.net identity framework.
First thing, according to my understanding, you can't merge your db context (MyDbContext) with 'IdentityDbContext', because context of asp.net identity framework tables has to be inherited from IdentityDbContext<YourUserTable>. But your other tables may inherited from DbContext.
Therefore you have to use two separate db contexts if you want to use identity framework build in method support, which is UserManager etc.
You can use your existing database with identity framework, you just need to correctly bind your database tables with identity framework EF code first approach using model binding.
There is a YouTube video tutorial which may help you to get some idea in order to achieve your task. Actually this video illustrates to use Identity 2.0 with existing database.
Part 1: https://www.youtube.com/watch?v=elfqejow5hM
Part 2: https://www.youtube.com/watch?v=JbSqi3Amatw
Hope this helps.
I'm not really sure what you're trying to achieve but check this question to see if it's of any help.
ASP.NET Identity DbContext confusion
Here's part of a walk-through I created. There are a few steps included specific to making it work with code first migrations but you should be able to accomplish what you want using these steps.
Start by creating a new ASP.NET MVC project. Call it Contacts if you want the included code to match. The authentication defaults to Individual User Accounts which is what we want in this case. Deselect Host in the Cloud for now. You can enter your publishing settings later. Once the project is created bring up the Package Manager Console and Install-Package EntityFramework. Now since we are doing Code First add a simple model class.
public class Contact {
public int ContactID { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
}
At this point you would usually add controllers and such but since this post is focusing on the data side of things we'll skip over all of that. Next we want to add our database context. Go ahead and add it right in the Models namespace.
public class ContactContext : IdentityDbContext {
public ContactContext()
: base("ContactContext") {
}
public DbSet<Contact> Contacts { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public static ContactContext Create() {
return new ContactContext();
}
}
A couple of things to note here. Since we're consolidating the Identity tables into our application's context we want to inherit from IdentityDbContext instead of just DbContext. Also, I prefer not to use the generated "DefaultConnection" that gets created in Web.config so I'm passing "ContactContext" as the connection string name to the base constructor. We'll modify the connection string in a minute. If you're typing in the OnModelCreating method Visual Studio should add the call to base.OnModelCreating but if not make sure you add it since it's essential for building the identity tables. Although not essential, you can configure the modelBuilder not to pluralize table names. Add a Create method which is needed for the Identity code to use this context. Also, as you add code you'll need to right-click and Resolve to add the appropriate using statements.
As promised, here is the modified connection string to be updated in the web.config in the root of the site. The name property is changed to something that makes sense for the application and the AttachDbFilename and Initial Catalog values are changed to something a little more user friendly than the auto generated name.
<add name="ContactContext" connectionString="Data Source=
(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\ContactContext.mdf;Initial
Catalog=ContactContext;Integrated Security=True"
providerName="System.Data.SqlClient" />
Now go to the Models folder and open the IdentityModels.cs file. Cut the ApplicationUser class from here and paste it into your Contact.cs file. Again you'll have to resolve a few missing namespaces. At this point you can safely delete the IdentityModels.cs file. Since we've eliminated the ApplicationDbContext we'll need to do a find on ApplicationDbContext and replace it with ContactContext in a few places. You should be able to do a clean build.

Entity Framework Exception: Invalid object name

I am trying to create database using Code First approach. When I run the following code I am getting the following exception. Is there anything wrong in the fields that I defined? How can we overcome this?
Exception:
An error occurred while updating the entries. See the inner exception for details.
Inner Exception:
"Invalid object name 'dbo.Dinners'.
Note: I do not have such a table (Dinners) in the database. The code is supposed to create the tables. I just gave connection string to identify the server as mentioned in EF Code First: Cannot connect to SQL Server. Should I change the connection string?
Connections String:
string connectionstring = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
The LibraryReservationSystem database is already existing database. It has no tables. I am expecting EF to create the tables.
The connection string I copied from a working LINQ 2 SQL application. Do I need to make any changes to it to supply to EF?
UPDATE
When I included the following code, the exception got changed. Now it says - "Invalid object name 'dbo.Dinner'.". It is now complaining about Dinner table; not Dinners table.
protected override void OnModelCreating(DbModelBuilder modelbuilder)
{
modelbuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
Original CODE
static void Main(string[] args)
{
string connectionstring = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (var db = new NerdDinners(connectionstring))
{
var product = new Dinner { DinnerID = 1, Title = 101 };
db.Dinners.Add(product);
int recordsAffected = db.SaveChanges();
}
}
using System.Data.Entity;
namespace LijosEF
{
public class Dinner
{
public int DinnerID { get; set; }
public int Title { get; set; }
}
public class RSVP
{
public int RSVPID { get; set; }
public int DinnerID { get; set; }
public virtual Dinner Dinner { get; set; }
}
//System.Data.Entity.DbContext is from EntityFramework.dll
public class NerdDinners : System.Data.Entity.DbContext
{
public NerdDinners(string connString): base(connString)
{
}
public DbSet<Dinner> Dinners { get; set; }
public DbSet<RSVP> RSVPs { get; set; }
}
}
REFERENCE
http://nerddinner.codeplex.com/discussions/358197
Entity framework - Invalid Object Name
Invalid object name 'dbo.TableName' when retrieving data from generated table
http://blogs.msdn.com/b/adonet/archive/2011/09/28/ef-4-2-code-first-walkthrough.aspx
The LibraryReservationSystem database is already existing database. It
has no tables. I am expecting EF to create the tables.
That's not correct. If the database exists EF doesn't create any tables in this database. EF can create the database if it doesn't exist. That is the default database initializer CreateDatabaseIfNotExists that gets applied if you don't change it explicitly. You can select two other initializers: DropCreateDatabaseAlways or DropCreateDatabaseIfModelChanges. But neither of those will only create tables in an existing database but instead delete the database completely and create it from scratch including all tables.
What can you do:
Either delete the database manually (in SSMS for example), then EF will create a new one including the tables
Or use the DropCreateDatabaseAlways initializer once to let EF create the database including the tables, then remove the initializer again
Or if you can't delete the database for whatever reason write SQL code in the Seed method that adds the tables to the database (Wrong, thanks to Mark Stafford's comment)
Or use Code-First Migrations (EF >= 4.3) to add new tables to an existing database when you have added new entities.
#Slauma's answer is the right one - the tables are created upon initialization. It's probably easiest to just delete the database and let EF create it (if you leave your connection string as is, it will create a database called LibraryReservationSystem on the local machine; you should probably specify an explicit host name if you're going to use the connection string in the config at this point).
You would need something along the lines of:
public class NerdDinnersInitializer : DropCreateDatabaseIfModelChanges<NerdDinners> { }
And you would also need to set the initializer in your Main method:
Database.SetInitializer(new NerdDinnersInitializer());
Word to the wise: NEVER deploy an application with an initializer like the one above. You can see this blog post about how to control initializers via the config file for more details on how to control this in production applications.
I've just ran into the exact same issue - I'd already created my database on a development SQL box inside our network that needs SQL authentication.
When I ran my app, no tables were created. I found this awesome but simple article about creating a Code First Database Initializer Strategy which first checks to see if the database exists and then runs a script against the database to create the tables.
As stated in the article - pay attention that when such a strategy is deployed, whenever the application starts over, all the database tables will be recreated! This strategy should only run once.
But you already knew that.
As the error suggests, you do not have a table called Dinners within your database.
Are you using Single or Plural table names? i.e. Dinner or Dinners?
As I understood, you are expecting the code to create DB automatically based on your entities description. But this will not happen unless you create DB explicitly. Please check the following link http://www.simple-talk.com/dotnet/.net-framework/entity-framework-4460---learn-to-create-databases-from-the-model/
and this tutorial on EF codefirst: http://codefirst.codeplex.com/
Once you have your entities designed you can right-click the workspace of the EDMX file and select 'Generate Database from Model...'. Click through until you have a script in your window. For that script you will have to remove DB creation step (if it is there) and go straight for CREATE TABLE ...
Copy-Paste and execute in whatever DB you've got. You might have to adjust the script for a specific RDBMS.

Can I change the default schema name in entity framework 4.3 code-first?

Currently I am deploying my application to a shared hosting environment and code-first with migrations has been working great except for one minor hiccup. Everytime I want to push the site I have to use the "Update-Database -script" option because I have to prepend every table name with [dbo] because by default the shared host creates a default schema name that is the same name as the database username.
If I log into my shared host and create a database, I then have to create a user. If I name that user admin, then the tables code-first creates while logged in as admin look something like this "[admin].[BlogPosts]". When the application runs all the tables are created but I get an EF exception because it says "[dbo].[BlogPosts]" is invalid. If I rename the table's schema name to "[dbo]" instead of "[admin]" that fixes it.
To get around this I have to generate a migrations script to be executed manually and add "[dbo]" in front of all the table names because the script only references the tables by their name, not by their schema and their name.
Is there an easy way to get around this? It would be so nice if all I had to do was publish the application and everything just worked. If it wasn't for the schema name discrepancy it would be a one click deploy and everything would be glorious.
For those using Entity Framework 6, just use the HasDefaultSchema method:
public class Contexto : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("MyDefaultDbSchema");
}
}
You could use the ToTable method to specify the schema name. If you do not specify the schema name, EF will by convention use dbo.
public class MyContext
{
private string schemaName = "Foo";
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>().ToTable("MyTable", schemaName);
}
}
In EF Code first, by default, everything is set up based on user access with a managerial access "DBO-Schema" in the SQL Server. But if a specific user is defined to work with a database that is common in shared hosting, then there will no longer be Dbo management access. This time the names of our tables are dbo.tableName, for example, someUser.tableName, and inaccuracy of this point makes it impossible to run the program. To modify and explicitly assign a user connected to a database. If you use metadata, the following method should be used:
[Table("MyTableName", Schema="MySchemaName")]
public class MyClassName
{
//Other Lines...
}
Or (Whether or not Fluent API is customizable as follows:)
modelBuilder.Entity<Blog>().ToTable("MyTableName", schemaName:"MySchemaName");
Notice the following:
a good reference for study:
http://www.c-sharpcorner.com/article/fluent-api-in-code-first-approach/
For database-first implementations, it's easy. Open the edmx file, right click -> Properties and set the default database schema.
For code-first, this article seems most promising: https://web.archive.org/web/20150210181840/http://devproconnections.com/entity-framework/working-schema-names-entity-framework-code-first-design
I would like to add since this is for C#, I have written one below for VB
Public Class ClientDbContext
Inherits DbContext
Public Property Clients As DbSet(Of Client)
Protected Overrides Sub OnModelCreating(modelBuilder As DbModelBuilder)
modelBuilder.HasDefaultSchema("dbo")
End Sub
End Class

Categories

Resources