EF6 Issue. "Invalid Object" dbo.Sales - c#

Writing an API and using EF Code First. It was working perfectly fine, then I moved the POCO Objects that I use to create the tables into a folder called POCO. Deleted the database as the ID's that I was using were all out for some reason, and no when I go to update the database using migrations I get the Invalid Object "dbo.sales" error and I can seem to find out what to do about this.
Can Anyone help?

You deleted your database and need to create a new database. You can't update it using database migrations, as there is no database to update.
Create a new database, and enable migrations.
Code First to a New Database
edit
In response to OPs comment.
To create a database using code first.
This tute is great.
Getting Started with Entity Framework 6 Code First using MVC 5
It's hard for me to give you specific advice, as I'm not sure what you've done to your project.

Related

Entity Framework core getting error when rerunning the Update Migration

I am working on asp.net core and using EF. I have created database from scratch using EF. Now whenever there are changes in the database, adding new columns, or changing the type etc. Then I run the Update-datebase migration but I am getting an error for having tables and other object in database. Can someone help me what changes would I need to make in order to make the migration successful?
The compile error mentioned that the object already exists. Lets say if I have customer table that is already created in the database, when I run the script again after adding new object or modification, I am getting that error, this does make sense but what is the common practice to deal with the issue?
As described in Migrations Overview after you are evolving your models (adding properties, removing properties, editing them and etc...) you need to update your database schema, in order to do that, you are required to add a new migration.
This can be possible in the one of following ways:
via .NET CLI
dotnet ef migrations add NewMigrationName
via PowerShell
Add-Migration NewMigrationName
After adding a new migration you just need to sync the database by:
Update-Database

EF Core 3.1 DB First to Code First update old database

The project at the moment is using Database first approach, now we are switching to code first for various reasons.
using Scaffold-DbContext I have generated DbContext (we already have, but probably it will be less error prone) from one of dev environments where they are latest changes applied. Removed the copied .HasConstraintName(""); and .HasName(""); in .OnModelCreating() and I've created the Initial migration. So far so good.
The problem comes with updating existing database which is old compared to latest and as well keep the data.
What is the best way to update the database with the migrations?
I've added this in the Configure() method under Startup.cs to create the database if doesn't exists with the migrations, but not sure how to update old, existing one which doesn't have migration history table.
if (!context.Database.EnsureCreated())
context.Database.Migrate();
One solutions is to create an initial migration from your old database and put the MigrationId (example : 20200609075705_Initial ) manually into the dbo.EFMigrationHistoryTable.
After that you can add new migrations without any problem .

Entity Framework Save not working

I am using Entity Framework to save some data in a SQLite database file.
This is my table in DB file
ID Name Username Pwd
ID is autoincrement, and rest of columns are of Text type
This is how I am saving my data into the database:
UserInfo userInfo=new UserInfo();
userInfo.Name="abc";
userInfo.Username="xyz";
userInfo.Pwd="123456";
using (var context = new ApplicationContext())
{
context.UserInfo.Add(userInfo);
context.SaveChanges();
}
The problem is, this code is not inserting any new row into the table. I also tried this before saving, but no luck
context.Entry<UserInfo>(userInfo).State = EntityState.Added;
context.ChangeTracker.DetectChanges();
I tried debugging and no exception is occurring.
How can I insert new row into a table using Entity Framework?
Possibilities that may cause an issue.
Right Click on your Entity Data Model and Update Model From Database. To make sure you have updated till the last change.
Make sure you are looking at the correct Database and Table. Every one makes this mistake once in a while.
Make sure you are using the valid connection string. Pointing the proper databases. Make sure its not a old db / some other backup db.
Make sure you are using the proper entity which is up to date.
The above code you have, its perfectly working fine to me. I just did a workout to sort out this issue.
The above points are guesses.
Refer this Link Entity Data Model Example & One More Example Code available here
I had a similar problem once and it can be a pain to determine what exactly causes this. One issue that might be causing such a behavior in EF is having multiple instances of the Context object such that when you call SaveChanges on your Context, you are actually calling it on a different instance than the one you added the entity on (and EF does not detect any changes in the entities or the new entity is not attached to the right context, causing SaveChanges to not send any SQL requests to the database).
I suggest debugging this in VS (using the object id feature) in order to see if you have multiple context instances. Using the Unit Of Work pattern together with repositories is a way to have a better control over the lifetime of the context objects in your application

EntityFramework 6.0 CreateDatabaseIfNotExists Code first to create database

What am I doing wrong. I have got a user DbContext setup and working when I originally created the Code-First with powershell it all worked fine.
I implemented Database Initializer as expected on application start.
Database.SetInitializer<UserDbContext>(new CreateDatabaseIfNotExists<UserDbContext>());
Just to test out if it really creates the database I actually dropped the database and now I am stuck the database will not be created. I am using SQL Server 2012, any idea what could be wrong.
The error message I am getting is
System.InvalidOperationException: Migrations is enabled for context 'UserDbContext' but the database does not exist or contains no mapped tables. Use Migrations to create the database and its tables, for example by running the 'Update-Database' command from the Package Manager Console.
I have tried the same from Package Manager console and it is still give me the same message.
Finally figured the solutions, not sure why or what. Changed my Database initializer to MigrateDatabaseToLatestVersion instead of CreateDatabaseIfNotExists worked.
Database.SetInitializer<UserDbContext>(new MigrateDatabaseToLatestVersion<UserDbContext, Configuration>());
Edit:
With your new error message the problem comes from you having migrations enabled and already ran a migration (probably the first creation of the database) and since you dropped the DB the migration history has been lost. If your not using Automatic migrations you can not go in and make changes to the database your self and expect code-first to know about it. Try disabling migrations and re-enabling them to see if that clears out the migration history.
You will need to make a call into the DB either as a read or insert of data for the DB to initially be created. The code you use only tells EF how to deal with a database if one does not exist when it tries to find it. For me I use the method outlined at http://www.codeproject.com/Tips/411288/Ensure-Your-Code-First-DB-is-Always-Initialized

Entity Framework Code First on external SQL server

I'm following the Entity Framework tutorial on:
Link
I've downloaded the source code, and ran. The project works fine (using the default connection string).
<add name="SchoolContext" connectionString="Data Source=|DataDirectory|School.sdf" providerName="System.Data.SqlServerCe.4.0" />
Next i've changed the connection string to connect to a remote server (which successfully connects). However the tables aren't created and when running the application and accessing the controller I get the following error.
Error:
Model compatibility cannot be checked because the database does not contain
model metadata. Model compatibility can only be checked for databases created
using Code First or Code First Migrations.
My database user is 'dbowner' so I wouldn't imagine it's database access issues.
I'm new to EF, and don't know much about Code First Migrations. Have you come across the above error, and would Code Migrations solve this issue? If so why?
From my reading (please correct me if I am wrong) the scenario here is that you have an existing (perhaps empty) database on a remote server that you wish to put your EF code-first work into.
The error is coming about because, I think, EF is looking for a _MigrationHistory table (metadata about what EF code-first migrations have been run against it etc) and can't find it. There is some reasonable coverage of this table here for some background/interest reading.
So to resolve the issue, I think the steps to take are:
Initialise your database so that it acknowledges the EF code-first stuff
Update the database, rolling forward all your migrations to date
I found some good coverage of how to do this here. This blog also has some good coverage of EF topics in general
PS. I am guessing that your .dsf/SQL Compact Edition database wouldn't have had this problem because EF code-first would have created it for you on first run so it was already acknowledged as being a code-first database.
Here is a link to Entity Framework Power Tools. It is made for creating models by 'Reverse Engineering' your Database on a remote server. You can then easily access this database using EF.
Reverse Engineer Code First - Generates POCO classes, derived DbContext and Code First mapping for an existing database
Both of the initializer methods which I had tried fail when the database already exists:
Database.SetInitializer<Context>(new Initializer());
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Context>());
However it is possible to force the database to be dropped using:
Database.SetInitializer(new DropCreateDatabaseAlways<Context>());
The following SO post provides the answer to my question:
Setting up a Entity Framework Code First Database on SQL Server 2008
I've tried a combination of the two, and have decided that the best solution is to manually go into SQL Management studio and DROP the database, and re-create it using the initializer as this allows me to Seed the contents of the database.
Database.SetInitializer<Context>(new Initializer());
See here for more information on Seeding the database as it is also quite an unstable processess!
How can I get my database to seed using Entity Framework CodeFirst?

Categories

Resources