Migrations after merging two DbContext with code first - entity-framework-migrations

I'm working on the legacy project with several DbContext to one Database. Now I need to add a relation between tables in different DbContexts.
class IdentityContext : IdentityDbContext<ApplicationUser>
{
...
}
...
class DepartmentContext : DbContext
{
DbSet<Department> Departments { get; set; }
...
}
I need to add the relation to IdentityContext - add the reference to Department from ApplicationUser.
For every DbContext, there is migration.
I want to merge both contexts into one. Something like this:
class IdentityContext : IdentityDbContext<ApplicationUser>
{
DbSet<Department> Departments { get; set; }
...
}
But when I run Add-Migration the new migration file contains code for creating a table Departments, but the such table I have already had in the database.
Where I'm wrong and how to skip creating the existing table in the new migration?

Related

EF Code First Cascade NULL

We have ASP MVC Entity Framework 6 Code First project with 70+ tables in a MS SQL database.
For each record on each table we are storing the user that has modified it the last. The structure of almost every table is like this:
public class TableA
{
public int Id{ get; set; }
.....
public DateTime? DateModified { get; set; }
public int? UserModifiedId { get; set; }
public virtual ApplicationUser UserModified { get; set; }
}
Our problem is we are getting an error when deleting a user if the user Id is in any of the tables' property UserModifiedId.
We need EF to set to NULL the UserModifiedId of all the tables where UserModifiedId = UserId.
In the past we setup this adding to the tables ON DELETE SET NULL, but EF doesn't allow to setup the tables like that.
Any idea how can we achieve this?
UPDATED
We already know EF manages this is the children are loaded into the context, but we can't load more than 70+ tables every time we want to delete a user.
One approach could be to add a migration that modifies all your tables that should have CASCADE ON DELTE SET NULL like that way (only for your example code above):
public partial class AddOnDeleteSetNull : DbMigration
{
public override void Up()
{
Sql("ALTER TABLE dbo.TableA DROP CONSTRAINT [FK_dbo.TableA_dbo.Users_UserModifiedId]");
Sql("ALTER TABLE dbo.TableA ADD CONSTRAINT [FK_dbo.TableA_dbo.Users_UserModifiedId_SetNullOnDelete] FOREIGN KEY (UserModifiedId) REFERENCES dbo.Users(UserId) ON UPDATE NO ACTION ON DELETE SET NULL");
}
public override void Down()
{
// Here you have to undo the changes!
// ...
}
}

Adding a view to database created by Code First

I have created my first ASP.NET MVC 4 application.
I have created my model which creates the Database (Database A). I now need to gather data from another database (Database B) which sits on the same server. I have created a view (2 columns - ID and Name called People) in Database A that shows me the data I require from Database B.
I'd like to add the view to my model and have typed the following
public class People
{
public int ID { get; set; }
public String Name { get; set; }
}
And added the following line to my dbContext
public class opsDBContext : DbContext
{
public DbSet<tbl_Operators> Operator { get; set; } // Existing
public DbSet<tbl_OpsWeekInfo> OperatorWeekInfo { get; set; } // Existing
public DbSet<tbl_OpsDayInfo> OperatorDayInfo { get; set; } // Existing
public DbSet<People> People{ get; set; } // New Line
}
But when i run project i get the following error
The model backing the 'opsDBContext' context has changed since the database was created. Consider using Code First Migrations to update the database
I think i understand why i get the message, i just want to me able to use the SQL View in my project, how can this be done?
Please let me know if you require more info
When a change occurs in classes of context or in your database, when you are using EF code first, you need to run migrations commands.
Take a look in this link :http://msdn.microsoft.com/en-us/data/jj591621.aspx

how to add new model in exist database

How can I add new model MVC in proper way?
I have one model with UsersContext. I want to create another - NewContext.
Is the code below will work without any problems? And maybe there is a better solution to create model in existing database? What exacly mean UsersContext and NewContext in code?
public class NewContext : DbContext
{
public NewContext ()
: base("DefaultConnection")
{
}
public DbSet<test1> test1{ get; set; }
public DbSet<test2> test2{ get; set; }
public DbSet<test3> test3{ get; set; }
}
(...)
Is the code below will work without any problems?
Yes, this will work. The DbContext is used to group the entities you want to work with in your application. In fact you do not need a second context. You could have only one DbContext in which you add all your domain entities as DbSet<T> properties and then work with this context.

Can EF Code First have two more DBContext in one App?

I have an ASP.NET MVC App, which use EF code First, for some reason I need to use 2 differents DBContext for my app like the example here:
namespace ESN.Models
{
public class CoreA
{
//..........
}
public class CoreB
{
//..........
}
public class CoreDbContext : DbContext
{
public DbSet<CoreA> CoreA { get; set; }
public DbSet<CoreB> CoreB { get; set; }
}
public class StuffA
{
//..........
}
public class StuffB
{
//..........
}
public class StuffDbContext : DbContext
{
public DbSet<StuffA> StuffA { get; set; }
public DbSet<StuffB> StuffB { get; set; }
}
}
And for the convenient developing I add some code that drop and re-create the database if model has change:
Database.SetInitializer<CoreDbContext>(new DropCreateDatabaseIfModelChanges<CoreDbContext>());
Database.SetInitializer<StuffDbContext>(new DropCreateDatabaseIfModelChanges<StuffDbContext>());
But the issue is they just Create new table for the DbContent that I need to use first, the Core table exist but none of the Stuff!
Thanks for your help!
If you want to use two DbContext types and database initializers each context must use its own database. If you use the same database for both context types you cannot use database initializers and you must maintain the database schema changes manually (you must manually or through some SQL script create database and all necessary tables prior to using the application).

Entity Framework 4.1 Code First: Single column foreign-key to multiple entities

I've been trying to create model in EF 4.1 to represent a database schema with a single table and column holding foreign keys from two other tables, but have had little luck with both annotations and the fluent API. A sample model is shown here:
public class User
{
...
public virtual ExtendedAttribute ExtendedAttributes { get; set; }
}
public class Account
{
...
public virtual ExtendedAttribute ExtendedAttributes { get; set; }
}
public class ExtendedAttribute
{
public Guid Id {get; set;}
public Guid ItemId {get; set;} // both Account.Id and User.Id stored here
public string Value { get; set; }
}
Currently the configuration for these entities looks something like this for both User and Account modelBuilders:
this.HasOptional(u => u.ExtendedAttributes).WithRequired();
Any thoughts on how to do achieve? Many thanks.
It is even not possible with the database itself and EF will not put any abstraction for that. You must have separate column and navigation property for each entity.

Resources