Consuming View in EF Code First conflicts with migration - c#

I have a Table "IncomingChecks" in my database. I've created it using EF Code first. Now, I've added a view to my database based on this table named "ViewIncomingChecks" using Sql Server Management Studio and I want to use its data in my app using Entity Framework.
I copied the model class and changed its name and added it to the context:
public class ViewIncomingCheck
{
[Key]
public int Id { get; set; }
//...
}
public class CheckDataContext : DbContext
{
public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks { get; set; }
//...
}
now when I run the app, it throws an exception saying the DB Context has been changed and needs a migration. I even tried to add a migration (which seems to be the wrong option) and when I add the migration, it says that the object ViewIncomingChecks is already in the database.
How can I use this view in my code?
Edit
My current solution is to have another context just for the views. This way it doesn't conflict with the EF Migrations. Is this the best option or is there a better way to deal with it.

According to what I have done in my project:
First add public virtual DbSet<ViewIncomingCheck> ViewIncomingChecks
{ get; set; } to your DbConext
Now create a migration something called ViewDbSetAdded
Remove all the code from the both Up and Down method and it will look like as follows:
Migration Code:
public partial class ViewDbSetAdded : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
Now run update-database command and it will run an empty migration.

Related

MVC - Using Custom Class for Model Property

I would like to preface this by saying, I am a web developer that started in C++ before learning ASP.NET C#.
So I have a Model in my web app that has a property that I would like use a custom class as the datatype of the property. I am not sure where to store the custom class in the folder structure in Visual Studio. Also, I am not sure I am setting this up correctly.
Custom Class
public class ClassName
{
public int value1;
public int value2;
}
public ClassName(int v1)
{
value1 = v1;
value2 = v2
}
Model
public class Model
{
public int ID { get; set; }
public string Name { get; set; }
public List<ClassName> ClassNames {get; set;}
}
I do not want the custom class on the database. I have been doing Code First with Migrations in Visual Studio and keeps trying to push the custom class into the database. Any ideas on what I could have setup wrong or what I need to do to get what I am looking for.
As far as folder structure -
Look into the Model View Controller pattern for Asp.Net, very nice pattern. Store your models in a folder called 'models', controllers under 'controllers' Views under 'views' etc.
as far as using 'classname' in your table, im not too sure if you can use classes for rows. not sure how the database table would accomdate that.
Perhaps you need to create another table for classname, and then reference those records back to your first table using a foreign key?
If you don't want the public class Model in the database then do an add-migration IgnoreChanges using the VS Package Manager Console.
This will create the migration class called IgnoreChanges and then in the public override void Up() and public override void Down() functions just delete any code you dont want.
like this:
public partial class IgnoreChanges : DbMigration
{
public override void Up()
{
// No code here
}
public override void Down()
{
// No code here
}
}
Perform an update-database and volia... no changes are added to the database.
You are basically fooling Migrations into thinking it has run your model into the database.
Migrations takes a snapshot of your database at the time you perform an add-migration so by removing the code you don't want published to the database, migrations will still recognise that your change has been generated, even though you removed the code from the public override void Up() and public override void Down() functions
Hope this makes sense

How do I get Entity Framework Code First Migrations to see my models?

I made a new ASP.Net Web Application and enabled migrations on it. I ran add-migration initial and the initial migration does in fact have all the default tables for authentication (dbo.AspNetRoles, dbo.AspNetUserRoles, etc). However, when I create my own context and add an entity model to it, I can't get migrations to acknowledge that model. That is, when I run add-migration added-watchedgame-model I just get an "empty" migration file. So what am I doing wrong? Does my DbContext have to be referenced somehow? can Entity Framework only handle migrations for 1 dbcontext?
ReleaseDateMailerDBContext.cs:
using System.Data.Entity;
using WebApplication4.Models;
namespace WebApplication4.DataAccess
{
public class ReleaseDateMailerDBContext : DbContext
{
public ReleaseDateMailerDBContext() : base("DefaultConnection") { }
public DbSet<WatchedGameModel> WatchedGameModelSet { get; set; }
}
}
WatchedGameModel.cs:
using System.ComponentModel.DataAnnotations;
namespace WebApplication4.Models
{
public class WatchedGameModel
{
public int ID { get; set; }
[MaxLength(1024)]
public string URL { get; set; }
public string Email { get; set; }
public bool EmailSent { get; set; }
}
}
"empty" migration file:
namespace ReleaseDateMailer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class addedwatchedgamemodel : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
"Batch Clean" may resolve your porblem.
It suggests that the EF tooling/assemblies are looking in a location other than the default build output location (typically /bin/Debug). The clean command also, incidentally, clears intermediary outputs.
To do a batch clean:
Select Build -> Batch Build
Click Select All
Click Clean
Close dialog, rebuild and re-attempt migration.
While running the add-migration command your package manager console should be pointed to the project having your DBContext class (WebApplication4.DataAccess).
If you have migration in a different project than your web application project (suppose WebApplication4.Web) then you should run the following command:
add-migration "MigrationName" -projectName:WebApplication.DataAccess -startupProjectName:WebApplication4.Web
Hope it helps!!
With the built-in asp.net mvc project, a DbContext class (ApplicationDbContext) is already
created!
When you enter enable-migrations, a migration configuration class is created based on the dbcontext class that it finds.
When you enter add-migration "migrationname", That dbcontext class is what is checked for differences.
So all one has to do is, rather than making one's own class that derives from DbContext, use that one.

Table not mapped using EF code first approach

I'd like to use EF code first approach. I added the database and I generate the tables . Then I added this class
public class Invitation
{
[Key]
public int Id { get; set; }
[DefaultValue(false)]
public bool State { get; set; }
public string Mail { get; set; }
public string Tel { get; set; }
public string Name { get; set; }
public string Qr_code { get; set; }
}
I run these command then :
add-migrations second
update-database
the Up and Down methods of the second class migration are empty!! and no table is added to the database.
The context
public class ApplicationContext: IdentityDbContext<ApplicationUser>
{
public ApplicationContext()
:base("DefaultConnection")
{
Database.SetInitializer<ApplicationContext>(new CreateDatabaseIfNotExists<ApplicationContext>());
}
public static ApplicationContext Create()
{
return new ApplicationContext();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
So I need to know
What is the reason of this problem?
How can I fix it?
Looks like you forgot to tell Entity Framework about the new table that you want added (DbSet<Invitation>)
Once you add this, Entity Framework should add the table(s) you want added in the Migration script, respectively.
In summation, you would need to add this line :
public DbSet<Invitation> Invitations { get; set; }
and/or
public IDbSet<Invitation> Invitations { get; set; }
and run another Migration Script.
Try adding the following into your ApplicationContext class
public DbSet<Invitation> Invitations { get; set; }
Then running;
Enable-Migration
Add-Migration note_of_changes
Update-Database
I think you need to create an initial migration. If this is your first migration (note that this will clear your existing migration history so only use if you're happy to discard your existing migration history)
Delete your Migrations folder in the solution
Remove your changes (remove the reference to the new table from your DbContext). Note that -IgnoreChanges could well make this step redundant but I can't say for certain.
Remove the MigrationHistory table from your database (it most likely won't exist but you can go ahead and delete it if it is)
Now enable migrations (in package manager console)
Enable-Migrations
Then create your initial migration. This will create a migration matching your existing schema with empty methods
Add-Migration Initial –IgnoreChanges
Update-Database
Then update your DbContext with your new table reference and make any other changes you need to and do
Add-Migration MyChanges
Update-Database
That should apply the changes to the database. Some more info over at MSDN if you need it.

Entity Framework 7 Update DbContext after migration

I've got an existing DB and new WPF project.
1) I scaffolded db context with Scaffold-DbContext and recieved DbContext.cs and a file for each entity that represents a DB tables. That's OK.
Here is example of one of them:
public partial class SomeEntity
{
public long SomeEntityID { get; set; }
public int SomeInt { get; set; }
}
2) I've manually updated this entity (no changes in DbContext.cs) :
public partial class SomeEntity
{
public long SomeEntityID { get; set; }
public int SomeInt { get; set; }
public string SomeString { get; set; }
}
3) I've used Add-Migration command. Now I've got a migration file that describes required changes and DbContextSnapshot.cs. Snapshot includes changes I've just made with SomeEntity. Database is not updated.
4) I've used Update-Database command. Database updated to match last migration. But my DbContext.cs doesn't know anything about changes in DB. It is still the same old good DbContext that I had after scaffolding DB.
Is this OK? Should I now change DbContext manually to match changes that I've made to my entities and applied them to DB? Is there a way to update DbContext.cs from DB after changes without 'rescaffolding'? (Because, for example, all comments and attributes in entity files will be lost, because they will be replaced with new ones if I use Scaffold-DbContext again)
You will have to run scaffolding again, but keep in mind that the generated classes are partial, so you can put your changes in another file

Set up database creation/migrations from code for Entity Framework 6 + MySQL

I've previously used NHibernate and Fluent Migrator in projects to create a database (if it didn't already exist) and update the schema through migration scripts. I'm looking over Entity Framework (6) to do a comparison and I'm having trouble replicating that functionality.
In my App.config, I've set up my connection string and db providers. I then went ahead and created a data model that I would like to be represented as a table in the database.
namespace DataModels
{
public class StoreClient
{
public int Id;
public string DisplayName;
public StoreClient()
{
}
}
}
I then went ahead and created a database context.
namespace DataModels
{
public class StoreContext : DbContext
{
public DbSet<StoreClient> StoreClients { get; set; }
}
}
On service start I created an instance of StoreContext and tried to add and call db.SaveChanges();, but this is failing because there is no schema that matches my StoreClient.
My question is simple. How do I configure my StoreContext (or EF in general) to automatically create my database schema, and how do I set it up to migrate when I make changes to that schema?
This seems simple, but my searching around hasn't gotten me anything that looks remotely familiar coming from the NHibernate world.
If you want your db to be created automatically try to put some code in your Application_Start() method.
for example:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext, Configuration>());
StoreContext context = new StoreContext();
context.Database.Initialize(true);
Where Configuration class is created upon automatic migrations are enables in the console. Check out this msdn demo.
Also i am not shure that your code firs model will work that way. If not try changing your fields with properties.
namespace DataModels
{
public class StoreClient
{
public int Id { get; set; }
public string DisplayName { get; set; }
public StoreClient()
{
}
}
}

Categories