Entity Framework 5, Code First and Add-Migration Using a Second DbContext Not Working - entity-framework

I have a problem with "Add-Migration" instruction when the Table definition is in a new DbContext Class.
I created a new ASP.NET MVC 4 Application in Visual Studio 2012.
I ran the "Enable-Migrations", "Add-Migration mig1", "Update-Database". Everything was smooth.
Than, I added a new class inheriting the DbContext to the Models folder. I was hoping that "Add-Migration mig2" will notice the new table definition. But it does not.
Any ideas why?
namespace MvcApplication4.Models
{
public class CmsContext: DbContext
{
public CmsContext()
: base("DefaultConnection")
{
}
public DbSet<CustomItem> CustomItems { get; set; }
}
[Table("CustomItems")]
public class CustomItem
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int Ordinal { get; set; }
public String Title { get; set; }
public String Content { get; set; }
public String FilePath { get; set; }
}
}

Multi-tenancy is not supported in EF5 but is supported in EF6 where you can specify a context for which you want to enable migrations for like this:
Enable-Migrations -ContextTypeName {NameOfTheContextType}
See the migrations multi-tenancy feature spec on the Entity Framework codeplex site.

Related

Fetch data from multiple related tables using Entity Framework core and display in view in Asp.Net Core

I am working on one Asp.Net Core application using Entity Framework Core. That app is basically into E Commerce. I want to fetch information of particular product from multiple tables which are related to each other using the master table product, and then i want to pass the data to the View. Can anyone help me in this regard. I am unable to find any perfect solution of Joins and pass the related data to View.
To complete these steps you need Visual Studio 2022.
Based on current documentation:
public class OrderDetail
{
public int OrderDetailID { get; set; }
public int OrderID { get; set; }
public int ProductID { get; set; }
public int Quantity { get; set; }
public Order Order { get; set; }
}
public class Order
{
public int OrderID { get; set; }
public int CustomerID { get; set; }
public int EmployeeID { get; set; }
public DateTime OrderDate { get; set; }
public List<OrderDetail> OrderDetails { get; set; }
}
It is a very simple model which contains only two classes, Order and OrderDetail has a one-to-many relationship. The next step is to add a new context class and make sure to inherit from the DbContext class
public class MyContext : DbContext
{
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(#"Data Source=(localdb)\ProjectsV13;Initial Catalog=StoreDB;");
}
}
Now to create a database using migrations from your model, install the following packages;
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design
Once these packages are installed, run the following command in Package Manager Console.
Add-Migration Initial
This command scaffold a migration to create the initial set of tables for your model. When it is executed successfully, then run the following command.
Update-Database to apply the new migration to the database. This command creates the database before applying migrations.
If you need to learn how to set up relationships the following websites have very good documentation and walkthrough on the entity framework.
I hope the following links help:
https://entityframeworkcore.com
https://www.learnentityframeworkcore.com

EF 6 How to skip existing tables when generating migrations

I am trying to use code-first within my existing project. I want to exclude existing entities from migrations I generate for new entities.
I have all models in separate class library project e.g. Data.Models and I am intending to use one context by creating another class library e.g. Infra.EF (model project is referenced in it).
This is how my DbContext looks like:
public DbSet<ExistingEntityOne> DataOfEntityOne { get; set; }
public DbSet<ExistingEntityTwo> DataofEntityTwo { get; set; }
public DbSet<NewEntity> NewData { get; set; }
Sorry if question isn't clear but I can add more information based on your feedback.
Thanks.
Remove Migration directory from your project.
Comment new entities in your new DbContext.
public DbSet<ExistingEntityOne> DataofEntityOne { get; set; }
public DbSet<ExistingEntityTwo> DataofEntityTwo { get; set; }
//public DbSet<NewEntity> NewData { get; set; }
Run following commands In power console manager:
Enable-Migrations
Add-Migration somename -IgnoreChanges
uncomment, commented entities.
public DbSet<ExistingEntityOne> DataofEntityOne { get; set; }
public DbSet<ExistingEntityTwo> DataofEntityTwo { get; set; }
public DbSet<NewEntity> NewData { get; set; }
Run following command:
Add-Migration someOtherName
You can find more, for EF Migrations here

entity framework code first not creating tables using VS 2012

I have a MVC4 Web api project under visual studio 2012 for which I would like to create and manage database using EF 6.0.2 code first. Actually, the solution entails four projects, namely,
OnlineShop.Application (User interface)
OnlineShop.Model dedicated to POCO classes only
OnlineShop.Test for unit tests and
OnlineShop.Core having UnitOfWork, GenericRepository and
DatabaseContext classes
Each of the mentioned projects includes an app.config which holds Same connection as that of web.config.
Problem: After running the project (in debug mode), the database is created as it's shown on server explorer (in visual studio 2012). But, it has no tables!!!
The database context class is also as the following:
public class DatabaseContext : DbContext
{
public DatabaseContext() : base("OnlineShopDb")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
}
//public static void InitializeDatabase()
//{
// using (var context = new DatabaseContext())
// {
// context.Database.CreateIfNotExists();
// Database.SetInitializer(new MigrateDatabaseToLatestVersion<DatabaseContext, Configuration>());
// }
//}
public DbSet<Person> Persons { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<Audit> Audits { get; set; }
public DbSet<RoleGroup> RoleGroups { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<UserInRole> UserInRoles { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<ProductCategory> ProductCategories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Entity<Person>().Map<User>(c => c.Requires("Discriminator").HasValue("User"));
}
}
I have surfed the web so much, found lots of articles ans samples regarding EF code first approach but unfortunately couldn't handle this bad problem!
I would appreciate it if anyone could help me on this.
Entity Framework code first does not create your database until you try to access it, so run your project and try to get or insert some record to your database.
another usefull tip is that if you change your models EF by default will throw an exeption, and you will have to drop the current database so EF can crate a new one.
or I recomend you to change that default behavior this way

How can Lazy Loaded entities be tested using a mock DbContext?

I am using the fake DbContext recommended by Microsoft for unit testing with EF5.
Everything is working fine, however I am using a "code first" approach, and some of the code under test is relying on lazy loading of related entities.
public partial class Entity
{
public int EntityId { get; set; }
public string EntityName { get; set; }
public virtual ICollection<EntityLifeCycle> EntityLifeCycles { get; set; }
public virtual EntityStatus PreviousStatus { get; set; }
public virtual EntityStatus CurrentStatus { get; set; }
}
Sample of usage:
if (entity.EntityLifeCycles.Count() > 0)
{
...
}
How can I modify my test code (and not the code being tested) to accommodate this?
Researched links for reference:
Testing With a Fake DbContext
Mocking your Entity Framework data context and testing it in .NET MVC

Code First doing strange migration when I add an interface to my entities

I have a strange problem with code first:
In project my entities looks like that and code first was doing migrations fine.
public class MyEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
}
I decided to add an interface to my project like this one
public interface IEntity
{
Guid Id { get; set; }
bool IsDeleted { get; set; }
}
My new class now looks like that:
public class MyEntity : IEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
bool IsDeleted { get; set; }
}
Now, if I try a migration with Code First, instead of adding a column here is what is doing code first:
DropForeignKey
DropIndex
Tries to CreateTable MyEntity table and breaks telling me this table already exists
Any idea why code first tries to do that?
Using EF5 I couldn't get it to repro. In general with migrations the order in which commands are executed is important so as the metadata is consistent between the database and models.
The correct order for these operations would be to either:
a) Run Enable-Migrations, Add-Migration then Update-Database before populating the database (i.e. running the app) then Add-Migration and Update database after each model change before running the app
b) run the app, Enable-Migrations, change the model, Add-Migrations, Update-Database, again making sure to run update the database after each model change is made
also note I am using a very simple DbContext that looks as such:
public class EntityContext : DbContext
{
public DbSet<MyEntity> MyEntities { get; set; }
}