Entity Framework multiple projects with code first migrations - c#

I have a class library project named "Core" which defines CoreContext with properties for common classes:
public class CoreContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<UserContactInfo> UserContactInfos { get; set; }
... more common properties ...
}
Then I have multiple projects referencing the "Core" project and defining new Contexts inheriting CoreContext:
Project1:
public class Project1Context : CoreContext
{
public DbSet<Foo> Foos { get; set; } //object defined in Project1
}
Project2:
public class Project2Context : CoreContext
{
public DbSet<Bar> Bars { get; set; } //object defined in Project2
}
When I change something in Project1Context I create a new migration in Project1 which is OK,
but if I change something in the Core project, lets say add property Company to UserContactInfo I will have to go to Project1 and Project2 and add new migration and I will end up with migrations related to the Core project in Project1 and Project2.
My question is: Is there a way I can keep the migrations for CoreContext in the Core project and Project1Context and Project2Context migrations to their corresponding project and automatically execute all migrations related to the project, so when I start Project1 it will run its own migrations and CoreContext migrations?
As clarification, I have separate databases for Project1 and Project2 and recently Updated EF to version 6.

What you are saying is not possible..
Just imagine if you are using model to create basic CRUD views and then changing the model. Your question is similar..

Perhaps you could write your own sub class which inherits from MigrateDatabaseToLatestVersion?

Related

ASP.NET MVC Code-First Building Empty Migrations

I am assuming there is something I am missing but when I generate migrations in a project, they keep showing empty Up and Down methods. Even in a brand new project. Here are my steps.
Launch Visual Studio 2019. Create a new ASP.NET Web Application (.net framework) C# project (4.7.2). Choose MVC and under authentication select Individual User Accounts. Click create to create the project.
Next I Enable Migrations.
Enable-Migrations
Next I add my first migration.
Add-Migration First
A first migration is successfully added with all the identity information for individual user accounts. All is good.
I update the database to apply the migration. All is still good.
Update-Database
Now, I add a new class to the Models folder called SchoolContext.
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace WebApplication6.Models
{
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public SchoolContext() : base("DefaultConnection") { }
}
public class Student
{
[Key]
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
}
I now go back to the Package Manager Console to create another migration. I attempt to create a new migration.
Add-Migration Second
But this time, the class is empty. it does not create my new table.
namespace WebApplication6.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class Second : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
What am I missing? Why doesn't it want to generate a migration with my new table?
As requested, this is what my ApplicationDbContext looks like in my IdentityModel.cs class generated by Visual Studio.
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
If your first migration created users tables, then I assume that it used IdentityDbContext. Then, you need to inherit your SchoolContext not from DbContext, but from IdentityDbContext.
UPDATE: based on the latest update of the question, it is clear that application already has one database context, which is ApplicationDbContext. So usually it is enough to keep all DbSet<> in one database context. No need to create new context.
You are missing the dbset property.
Put it as following example so that migrations can detect the new class/table.
After adding the dbset property, add new migration to see the new class written.
If you already have a migration pending then write -force for the code to see new changes and update migration
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection") {
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
public virtual DbSet<Student> Students { get; set; }
}
Note that there are 2 dbcontexts which is not of clear use, use only ApplicationDBContext and remove the other.

Entity Framework and empty migrations class

In my solution I have two projects: SharePoint and Class Library. In ClassLibrary is a class DBContext and models. "Enable-Migration" generated class Configuration.cs. Next, I created the first migration through the "Add-Migration Initialize" and it worked. My next step was to "Update-Database" everything was fine. But after a while I changed the model and I wanted to generate migration. Unfortunately, I get a blank method Up and Down. Entity Framework does not see my changes ... The models are written without annotations and Context it inherits DbContext and is written like this:
public class SchoolContext: DbContext
{
public SchoolContext (): base () {}
public DbSet <Student> Students;
}
Models are written in this way:
public class Student
{
public int FirstName {get; set; }
}

ASP NET MVC 3 - How to reset database in code first, with two tables and Database.Setinitializer?

My problem lies in the lack of experience in MVC. Basically, I have two tables in DB
-Person
-Offer
For each I have created a model and a controller and a model, so the structure looks like that:
public class Offer
{
public int OfferID { get; set; }
public string OfferTitle { get; set; }
public string State { get; set; }
public string Description { get; set; }
}
public class OfferDBContext : DbContext
{
public DbSet<Offer> Offers { get; set; }
}
This is the Offer model.
public class Person
{
public int PersonID { get; set; }
public string Username { get; set; }
public DateTime Birthday { get; set; }
public string Education { get; set; }
public string Email { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> Persons { get; set; }
}
This is the Person model.
Firstly I created the Person model, that added itself to db without any problems. Then I wanted to add Offer table, and I had to use the DropCreateDatabaseIfModelChanges method. I used it for OfferInitializer and PersonInitializer and then there is the Global.asax.cs file
protected void Application_Start()
{
Database.SetInitializer<OfferDBContext>(new OfferInitializer());
Database.SetInitializer<PersonDBContext>(new PersonInitializer());
//Database.SetInitializer<PersonDBContext>(new PersonInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
From what I understand, I cant do that simply because I am dropping database 2 times, each time populating only one table at a time. How do I reorganize it all, so that I can populate both or more tables at a time, or the whole database?
First things first, you should not create individual DbContext classes for each table. You should instead put all your DbSets in the same DbContext. Doing this will simplify things greatly for you.
Secondly, you should look into using migrations. You should start using them very early in your project.
You work with code first migrations using the Package Management Console.
enable-migrations
Does exactly what the name implies. Initializes migrations in your project. This will create a folder inside your project and generate the files needed.
add-migration InitialCreate
This creates a migration. InitialCreate is actually a string and you can change it to whatever you want. This command will generate the scripts needed to create the database from strach.
update-database
This command verifies the database and applies the migration (or migrations - there can be multiple) required in order to get the database up-to-date.
This is the initial setup. If you do further changes to your first code first classes, or add more, you will just have to add a new migration and then execute it.
add-migration AddedFirstName
update-database
It's that simple!
There are some more advanced concepts like seed, rollback, update to specific migration, etc., but what I have typed above covers the basics and the day to day usage of migrations.
I recommend you to read this article which explains everything in much more detail: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application

C# .Net class library database schema create

Im creating a class library that will be used in several projects. This library includes a handfull of entities with associated tables in the database. My question is: how do I create these tables when I include this library in a project?
I suspect you want a library of objects that are used to generate a database?
If so you can achieve this with EntityFramework CodeFirst.
At minimum you'll need your objects and a DbContext.
a typical set up maybe as follows:
Entities
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
DbContext
public class MyDbContext : System.Data.Entity.DbContext {
public MyDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
public DbSet<Person> People { get; set; }
}
These would live in your project and when you add a reference to it, for example a web project. There are different ways to build the Database, you could call the constructor (MyDbContext) from your web project and pass a connection string to a server.

Difference between .edmx file and creating an Entities.cs file

I have looked at two of Microsoft's tutorials for MVC. In one tutorial they are creating a .edmx file to handle the Entity Framework in order to execute Linq queries. In another tutorial they made a class called "MusicStoreEntities.cs" here is the code:
using System.Data.Entity;
namespace MvcMusicStore.Models
{
public class MusicStoreEntities : DbContext
{
public DbSet<Album> Albums { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Cart> Carts { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
}
}
And the tutorial creates an instance of this class and starts doing Linq queries as well. What are the differences between these 2 methods? and how can I make DbSet objects in a .edmx file? Thank you.
There are various ways to create your model structure.
You can code POCO classes first, and create the database manually.
You can code POCO classes first, and create the database automatically using code first libraries.
You can create your database schema, and import it into a class diagram (which will supply all the models and navigation).
You can create your class diagram, and create your database schema from that.
1 and 2 create only the cs, while 3 and 4 create the edmx.
You can check this for Code First EF (this includes the DbSet part of your question).
EDIT: You can even use POCO classes with an existing database, as posted here.

Categories

Resources