What is the best way to use migrations with MVC5 and .Net Identity? - asp.net-mvc

I'm just putting myself through the paces learning MVC5 with EF6 and Code First and have run into some confusion...
How are people managing their DbSets with the Identity changes, especially with Migrations?
Are you managing two sets of Migrations or putting your normal DbSets into the IdentityModel.cs file?
This is what I have currently:
public class ApplicationUser : IdentityUser
{
}
public class AoecContext : IdentityDbContext
{
public AoecContext()
: base("DefaultConnection")
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Faculty> People { get; set; }
public DbSet<SitePage> SitePages { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<SitePage>().HasOptional(p => p.CourseDetails);
}
}
Is that a good idea, or just plain bad?

Your concerns are a bit better separated if you keep your IdentityDbContext separate from your DomainDbContext, but then you would need to manage two sets of migrations (among other things). As you have it you'll only need one set of migrations. I wouldn't consider what you're doing "bad" necessarily- it really depends on the project.
If its any consolation, the project that we are currently working on uses only one DbContext that also inherits from IdentityDbContext as yours does. It does pull in some references to the Data Access project that I wish weren't there, but it does greatly simplify working with EF in terms of database generation, persistence, and migrations. Whether we'll outgrow it in the future or not is hard to say.

Related

asp.net mvc enable on delete cascade for entire project

I've searched for something that solves my problem, but don't seem to find anything.
Is there a way to simply enable OnDeleteCascade for the entire project?
Can anyone help please?
You want to setup your relationships in your DbContext and specify your cascade deletes in your model builder.
public class SomeContext : DbContext
{
public DbSet<EntityOne> EntityOnes { get; set; }
public DbSet<EntityTwo> EntityTwos { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityOne>()
.HasRequired(d => d.EntityTwo)
.WillCascadeOnDelete(true); // this is what you want to do
}
}
Reference: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-a-more-complex-data-model-for-an-asp-net-mvc-application
Reference (This one is really good for various relationships): https://msdn.microsoft.com/en-us/library/jj591620(v=vs.113).aspx
EDIT: Wanted to note this is called Entity Framework Fluent API if you wanted to google for some more info.

How Migration Works in Repository Pattern

Currently I am developing Large N-tire Application in Asp.Net MVC and
want to Separate Data,Entity,Service,Repository(Generic repository
with Unit Of works) I have reference Long Le article in Class
library project so I can reuse code in both controller and in Web API
Controller with code first entity framework and migration occurs if
model is changed.So,please suggest best approach for above
understanding?
As I have created separate project is there any effect in future while doing migration ?
You don't need repository pattern with Entity Framework Code First, because DbContext implements repository pattern and unit of work.
I usually define common database interface. Something like that:
public interface IDatabase
{
IDbSet<Plan> Plans { get; set; }
int SaveChanges();
}
Then I implement interface with my DbContext:
public class MyContext : DbContext, IDatabase
{
public IDbSet<Plan> Plans { get; set; }
// ...
}
You can create a context for testing purposes
public class MyMockContext : IDatabase
{
public IDbSet<Plan> Plans { get; set; }
// ...
}
But in your controller you always dependency-inject IDatabase. So that it's not dependent on any concrete implementation (and I use EFMock library in my tests).

Overly complicated many-to-many relationship with ASP.NET MVC

While researching whether or not ASP.NET MVC is suited for my next website, I've come across an annoying issue.
I have followed ASP.NET MVC since version 2, and it's gotten better. For instance, it's now fairly easy to get going with migrations in the entity framework with code first, which used to be a hassle.
This means that I now can get running with a database migrations and code first within half an hour (as I usually don't remember the steps involved, I have to follow a guide I wrote).
Now, fairly early on I always get a many-to-many relationship between entities (e.g. tags and posts) in my database, and what I've found is that getting this relationship exposed via MVC framework is surprisingly complicated! Example from asp.net Example from mikesdotnetting
It involves special methods to retrieve the relationship's data that is not an inherent part of the framework.
Is there really no better/easier way of treating the many-to-many relationship?
You should add a virtual key word to the Many port
public class Post
{
[Key]
public int ID { get; set; }
public string Title { get; set; }
public virtual ICollection<Tag> Tags {get;set;}
}
public class Tag
{
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<Post> Posts {get;set;}
}

How dependant is breezjs serverside contexprovider to entityframework?

I am building a WebApi for a CMS that has its own data provider. No DBContext or entity framework involved.
I have previously used breeze as it being such a breeze to map the server side model to the client:)
I have wondering if I can extend my code or breeze in a way such I get all the stuff from brezejs for free.
What I have to work with is the following Interfaces that I have made implementations for based on the data provider from the CMS.
public interface IC1Repository<T>
{
IQueryable<T> GetAll();
T Add(T item);
void Remove(T item);
bool Update(T item);
}
Its generic, so thats not going to work on the client.
I can generate a context class i guess that holds all the types exposed.
public class mycontext
{
public IC1Repository<Category> Categories { get; set; }
public IC1Repository<Customer> Customers { get; set; }
public IC1Repository<Employee> Employees { get; set; }
}
What would my next steps be to get this workign with breeze. Are there any interfaces i can implement such it mimics the DbContext. Can i maybe crate my custom DbSet that do not talk with a database, but just is a implementation of my IC1Repository above?
Any advices thanks :)
I think you want the ContextProvider which is the base class of the EFContextProvider.
That has the same semantics and same base behavior as the EFContextProvider but it doesn't use EF.
Check out the "No DB" sample which uses the ContextProvider to manage queries and saves to an in-memory "database".
Ignore the fact that this class sits in a DLL with references to EF. I realize that is annoying. But your project will compile and run just fine when there are no EF assemblies around. You can delete all the EF stuff if you used NuGet to get the Breeze.WebApi.dll.

How to use different Entity Framework DbContext in the Area of ASP.NET MVC application?

Currently I am building a web application with MVC 4 and Entity Framework code first scenario.
In the main structure of my application, I have a Dbcontext(BlogDB) to manage some Blog classes. It works fine as it created all the tables I need in the database. Then I created a Area to host an online store. My idea is to create a separated DbContext class(OnlineStoreDB) to handle the classes used for Online Store only.
My problem is once the OnlineStoreDB is fired, entity framework not only created tables for OnlineStore BUT ALSO removed old tables.
My questions are:
If you know a way to keep the old tables?
How exactly to manage the multi EF context classes in one application?
Code:
public class BlogDB : DbContext
{
public BlogDB ()
: base("DBConnection")
{
Database.SetInitializer(new BlogInitializer());
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Comment> Comments { get; set; }
}
public class OnlineStoreDB : DbContext
{
public OnlineStoreDB() :
base("DbConnection")
{
Database.SetInitializer(new OnlineStoreInitializer());
}
public DbSet<Order> Orders { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<User> Users { get; set; }
}
Xavier, welcome to code-first!
Yes, code-first was a brilliant approach that promised soooo much. But now you've hit the catch. There's no clever mind at Microsoft (or outside as far as I know) who has come up with a smooth way to alter tables intelligently without endangering the data and possibly schema.
2 Years ago, the implementation strategy was to drop and re-build the DB. That was just intolerable as many of us didn't have SU access and were stopped in our tracks.
For all the advantages I found from code first, I prefer DB first. While data can't be preserved easily, annotations can through buddy classes.
Microsoft has come up with some clever Migration Strategies. I strongly suggest you read both articles. Code Project 2nd:
1) http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-code-based-migrations-walkthrough.aspx
2) http://www.codeproject.com/Articles/504720/EntityplusFrameworkplusCodeplusFirstplusMigrations
whether you decide to continue with Code-First, they should be enlightening. I sound like a critic but I'm torn between advantages of one and stability of the other.
Finally, I don't think you should preserve 2 dbcontexts. Your POCOs should be consolidated under 1 context.
If you want to keep the tables not changed you need to set initializer to null in both DBContexts if they have sub set of tables .
But I don't see a point that you create two DBContexts for one database. Can you clearly separate two set of tables(Domains) in you database?

Resources