MVC 4 Simplemembership own contextclass - asp.net-mvc

I'm trying to implement the simplemembership with my own context class like so:
public class DbInitializer : DbContext
{
public DbSet<Car> Cars { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
}
This work fine and I get all the tables I need: Cars , UserProfiles, Webpages.Memberships, Webpages.Roles, WebPages.UserInRoles. But when I move all the model classes to another project and run it I only get Car and UserProfile so I'm wondering what more I have to do to get the rest of the tables?

Take a look at the SimpleSecurity open source project for an example of how to put SimpleMembership in its own context. Additional entities are also added to the project to enhance the security model. This is developed as a class library that can be incorporated into any MVC application.
You did not provide enough information to figure out what went wrong when you moved it to a new project. My guess is that you did not call WebSecurity.InitializeDatabaseConnection. Take a look at this article on customizing SimpleMembership which shows the best way to initialize the database.

Related

Dynamically change models and controllers after publishing website in ASP.NET Core MVC

I'm using ASP.NET Core MVC 2. I need to operator can change some elements of Models or view codes. How I can code or design for it.
For example: I have a "news" model and I want to operator (final user of website, who can't code or access to visual studio) can add this to "news" model:
public string ImageUrl { get; set; }
and also can change the database without coding.
Thanks
If you want to design a completely extensible model, you could use something called Entity–attribute–value model (EAV).
Your model might have a couple common attributes like Title and Summary. Then you might have a list of Custom Fields, the first of which could be ImageUrl. You could create your own class called CustomField or something similar, which would have properties such as FieldName, and DataType.
public string Title { get; set; }
public string Summary { get; set; }
public List<CustomField> CustomFields { get; set; }
You would then have a table full of custom field values and the tables they belong to. It gets pretty complex.
When you want to automatically reflect your model changes to the database, you will need an ORM framework like EF (Entity Framework). You can check more here.
In order for your case to happen is to build your own configuration platform that may use several tools and mechanincs that will allow you to generate code and then compile it. Such as T4 and more.
In general, this is a very hard task to accomplish and even big experienced teams would have troubles to build something similar.
I can not post any code, as this would only seem a desperate approach.

Where is UserProfile or ApplicationUser model class inside MVC 5 application

I have a hard time finding UserProfile/ApplicationUser in the MVC 5 application. I would like to add this field: public virtual ICollection<Meeting> Meetings { get; set; } to UserProfile/ApplicationUser class.
I want do this to use Mr. Chris Pratt's advice: How to associate list of objects with user(Account) in ASP .NET MVC
EDIT: Will Entity Framework will understand the association between Meeting and USER if I add in class Meeting field public int ApplicationUserId { get; set; } in code first approach?
I got only this:

moving mvc5 account controller code to separate project

I have a solution that contains a WebApi2,MVC5 & DAL project (all RTM).
I am wanting to use the new membership bits that are now baked-in, but I don't like all the account stuff being all in the account controller. Doing a file new project (asp.net) has all of the membership stuff coupled to the account controller.
Within my DAL I am using EF6 as I like the ideal of code-first as it suits what I am trying to do. I am trying to take the account controller code and move it into my separate project.
My context within the DAL is nice and simple (taken from the MVC site)
public class ApplicationUser : IdentityUser
{
//a user can belong to multiple stores
public virtual ICollection<StoreModel> Stores { get; set; }
}
public class DataContext : IdentityDbContext<ApplicationUser>
{
public DataContext(): base("name=DefaultConnection")
{
}
public DbSet<Business> Businesses { get; set; }
public DbSet<ConsumerModel> Consumers { get; set; }
public DbSet<StoreModel> Stores { get; set; }
}
From my account controller within my login actionresult I try
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user != null)
{
It throws an error with User.FindAsync
The entity type ApplicationUser is not part of the model for the
current context.
What do I need to do to allow ApplicationUser to be used in the current context?
I have done something similar. In order to implement separation of concerns, I fetch the UserManager from my Repository and then use it in the Presentation layer. Repository internally creates the UserManager from UserStore using the internal LoginDbContext. That way, the DbContext and Store are separated from the controller.
If you create WebApi project or somthing with VisualStudio template,
please carefully see UserManagerFactory = () => new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); in Startup.Auth.cs file.
You might miss (new ApplicationDbContext()) part. By default, it has empty parameter.
You need to create a UserManager which takes in the userstore which takes in your dbcontext
public UserController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public UserManager<ApplicationUser> UserManager { get; private set; }
public UserController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
I believe this will help. I am pretty new to MVC5 and I have been wanting to separate my model layer from my MVC website, mainly because I imagine I will want to share the models across my various projects. I have been unable to follow all the programming mumbo jumbo I have found on the various help sites. I always end up with a lot of errors which I am unable to resolve with my limited knowledge. However, I have found an easy way to move my ApplicationDbContext out of my MVC5 model and with hardly any errors. All the work is done by the wizards already provided by Microsoft. I would like to share my little find with everyone. This is what you do (step by step):
1. Create a MVC5 project with authentication. Call it ModelProject.
2. Exclude everything from the project except
a. Properties
b. References
c. Models
d. packages.config
3. The ModelProject will hold all your models (even ApplicationDbContext.) Rebuild it.
4. Now, create a new MVC5 project with authentication. Call this Mvc5Project
5. Import the ModelProject project into Mvc5Project .
6. Wire the ModelProject into this project i.e. link in the reference.
7. Exclude the following from the MVc5Project from the Models folder
a. AccountViewModels.cs
b. IdentityModels.cs
c. ManageViewModels.cs
8. If you rebuild now, you will get a bunch of errors. Just go to the errors and resolve them using the right click method to get the new namespace from ModelProject. The namespace will show if you have wired the project in correctly.
9. Also, dont forget to go to View/Manage and Views/Account of Mvc5Project and change the models in there to the new location otherwise you will get some weird cryptic errors.
That's it! Now you have a project with the models all separated out (including the applicationDbContext) -And NO ERRORS!! Good luck!

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?

How do I use my own Model classes in conjunction with EF entity classes in MVC?

So I am new to MVC and am working now with MVC3 and the Entity Framework. I am currently using a Model/Schema 1st approach as the database already exists. Therefore I create my ADO.NET Entity Data Model (.edmx) and I have all the needed entities in my MVC app. So far so good on all this.
However let's say one of my Entities is a 'Customer' entity. I can see the auto-generated partial class inheriting from EntityObject in MyEntites.Designer.cs. At this point I want to add some custom business logic to my MVC Model. Natuarally I believe the answer is to use my own partial class created in the Model named 'Customer' as well.
I did a lot of searching on this before asking the question and see all kinds of information on POCO, T4 templates, modifying auto-generated code, etc and am lost. Is it a royal pain to add my own business logic and custom code to the auto-generated entities from EF? I certainly don't want to modify the auto generated code over and over.
I need a straight forward explanation to make the proverbial 'light bulb' go on, and then I can take-off from there. Can someone help me answer how to do this please?
Thanks!
Keep your own class code in a different file, but use the same class and namespace. This will help avoid your code being overwritten by the T4 code generator.
Extending Entity Framework Generated Types
You can also add attributes to generated classes by using a meta class:
Adding Attributes to Generated Classes
Those codes are auto-generated and will be over written on each model update or change.
You can achieve what you need through extending models. Suppose that EF generated the following entity class for you:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public virtual UserProfile User{ get; set; }
}
}
and you want do some work arounds to preserve your you data annotations and attributes. So, follow these steps:
First, add two classes some where (wherever you want, but it's better to be in Models) like the following:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
}
}
then add what properties and attributes you want to the second class - NewsAttribs here. :
public class NewsAttrib
{
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
Notes:
1) The namespace of the generated entity class and your classes must be the same - here YourSolution.
2) your first class must be partial and its name must be the same as EF generated class.
Go through this and your attribs never been lost again ...

Resources