I have an existing ASP.NET MVC 4 web app where all code files resides in one project:
Satinge (.NET Framework MVC 4 web application project)
I am now reorganizing the app into presentation, data and services layers:
Satinge (.NET Framework MVC 4 web application - presentation layer project)
Satinge.Data (.NET Framework class library - data layer project)
Satinge.Services (.NET Framework class library - services layer project)
I have moved all data models and migration files to the data layer and so far the app builds fine and works when I try running it in debug mode. However, when I try adding a new model it won't let me run Add-Migration command in the Package Manager Console (Default Project: Satinge.Data). I am getting the following error:
Unable to generate an explicit migration because the following explicit migrations are pending: [--list of all migrations--]. Apply the pending explicit migrations before attempting to generate a new explicit migration.
It wants me to apply migrations that has already been applied to the database.
When I try running Update-Database, I get an error saying:
There is already an object named 'Name of Existing Table' in the database.
I'll assume you work with EF6 as EF Core uses different table layout (and does not include namespaces in the DB so you'd probably not have this issue in the first place).
As EF needs to track your actual DB state for migrations, it uses a special table called __MigrationHistory (which can be renamed if need be). Since your migrations are good ol' C# classes - the engine needs to then somehow figure out which of these got applied already. EF developers chose to opt for fully qualified class names. This is exactly what ContextKey column on that table is for.
So ultimately you have two choices - either update the table or define custom DbConfiguration to use different namespace:
public class MyDbConfiguration: DbConfiguration
{
public MyDbConfiguration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "Old.Migrations.Namespace";
}
}
...
[DbConfigurationType("MyNamespace.MyDbConfiguration, MyAssembly")] // there are few ways to plug it in: https://learn.microsoft.com/en-us/ef/ef6/fundamentals/configuring/code-based
public class MyContextContext : DbContext
{
...
}
Related
I have an ASP.NET Core 5.0 MVC application and a .NET 5.0 class library called Application.Data. Due to separation of concerns, I decided that the DbContext and migrations should be contained within the data library. The DDL migrations work perfectly, but I'm having issues seeding AspNetCore.Identity users from within the data library.
Simply put, I want to access a UserManager<MyUser> instance in order to invoke the CreateAsync/AddToRoleAsync methods, but the UserManager constructor takes eight parameters that then also need to be instantiated. My understanding is that I could inject the user manager using the AddIdentity method to the service collection of my MVC project, but since my DbContext is contained within Application.Data, I wouldn't be able to run migration commands from within the MVC project.
What is the best course of action here?
I have started to play around with ASP.NET Boilerplate framework. I want to keep my application-specific entities and services in two separate projects. This will keep the core framework project untouched.
However I am not sure if i have the entities in a separate project how will the migrations work. The module system in the documentation touches about the logic piece, but it does not talk about entities that are local to the module (so each module has its own entity that gets created when migrations take place).
What options do we have if we need to separate our entities and services to individual projects?
However I am not sure if i have the entities in a separate project how will the migrations work.
Migrations work based on the DbSet that you define for each entity in DbContext.
What options do we have if we need to separate our entities and services to individual projects?
So you can have the entities in a separate project.
Add a dependency on YourSeparateCoreModule to *EntityFrameworkModule:
[DependsOn(
typeof(AbpProjectNameCoreModule),
typeof(YourSeparateCoreModule), // Add this
typeof(AbpZeroCoreEntityFrameworkCoreModule))]
public class AbpProjectNameEntityFrameworkModule : AbpModule
Then add a DbSet for each of the entities.
I'm creating my 4th migrations script with EF Core (2.0.0). In there I want to add a few roles to the database.
The problem is, is that I'm not really sure how to do this. Currently I have this:
protected override void Up(MigrationBuilder migrationBuilder)
{
// todo: Pass connection string somehow..?
var opt = new DbContextOptions<ApplicationContext>();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationContext(opt)));
//if (!roleManager.RoleExists("ROLE NAME"))
//{
// todo: create the role...
//}
}
But creating the RoleManager like that gives me the following error:
There is no argument given that corresponds to the required formal
parameter 'roleValidators' of
'RoleManager.RoleManager(IRoleStore,
IEnumerable>, ILookupNormalizer,
IdentityErrorDescriber, ILogger>)'
I'm not sure how to solve this problem. I couldn't find any info on how to do this properly in .NET Core using migrations.
I'm facing two issues in this code:
I'm trying to create an instance of the DbContext somehow. Shouldn't I be able to get the DbContext from within my migrations code?
Instantiating the RoleManager like this doesn't work and needs to be resolved.
How can I solve these problems?
The Up method is basically an instruction file that tells EF's database migrator how to generate a database upgrade script. The method is executed when the script is generated. Doing any data manipulation there is absolutely out of place. EF core doesn't support seeding yet, so you have to add missing roles when the application starts, for example by something like this.
I created a quite simple plugin for Dynamics CRM 2013 that should populate some attributes based on some other attribute values.
The following error message occurs when query data:
Unexpected exception from plug-in (Execute):
Foobar.IsoCountry.Plugins.PreAddressCreateUpdate: System.TypeLoadException: Inheritance
security rules violated while overriding member:
'Microsoft.Crm.Services.Utility.DeviceRegistrationFailedException.GetObjectData(System.Runtime
.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'.
Security accessibility of the overriding method must match the security accessibility of
the method being overriden.
The code is quite simple:
var context = localContext.PluginExecutionContext;
var orgServiceSystem = localContext.OrganizationServiceAsSystem;
var target = this.GetTargetEntity(context).ToEntity<Account>();
using (var xrm = new XrmContext(localContext.OrganizationServiceAsCallingUser))
{
var list = from account in xrm.AccountSet where account.Name.StartsWith("foobar")select account;
///...
}
I am using the lasts SDK Version (6.1.1) and targeting Dynamics CRM Online (Spring Wave Update is installed).
The only think that might be a bit special, is the fact that I am usiong ILMerge to combine multiple dll into my plugin.dll.
Solved, I used an dedicated Visual Studio project for the data-access (repository pattern) and part of this project was a class (BaseXrmFactory) that used the "DeviceIdManager" class("DeviceIdManager.cs"; part of the SDK).
The class was used to created new instances of the org-service:
...
private ClientCredentials GetDeviceCredentials()
{
return Microsoft.Crm.Services.Utility.DeviceIdManager.LoadOrRegisterDevice();
}
...
Via ILMerge was this project include in my plugin-dll that was deployed to the CRM. Once I removed the class (DeviceIdManager) the plugin executed as expected :)
I do not fully understand way this was the problem because the BaseXrmFactory was NOT invoked as part of the plugin execution.
I had two plugins first with Isolation mode Sandbox and second with isolation mode None. I set all isolation mode to none and after all working correctly.
Clarified Updated Question - Start
In the official MVC 3 Getting Started-tutorial it seems to me that all we have to do to get ORM working are two steps.
First adding the simple MovieDBContext-code as described at the end of part 4 ..
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
.. and second in the beginning of part 5, with a simple right-click on the Controllers folder we can auto-generate a MoviesController that implements CRUD()-functionality using Entity Framework by simply telling which Model to use.
Now when using the web-application we can already write and read from the database.
What would be the simplest (or a simple) way to get this done for our Movie-Model with NHibernate instead of using Entity Framework?
Clarified Updated Question - End
Original question (only for additional background-info):
I'm trying to create an ASP.Net MVC 3 application that uses NHibernate and Postgres.
Background Info
Development is done on Windows with Visual Web Developer Express, the production environment will be/should be Linux+Mono.
Steps that have worked so far:
An ASP.Net Dynamic Data Entities Web Application using Npgsql and Postgres as the DB.
Successfully run on Windows development machine.
(Following this tutorial)
An ASP.Net MVC 3 application without using a database/model yet:
Succesfully run on Windows development machine and deployed to Linux production environment using Mono and Nginx. (Only as a proof of concept for myself not as a web app used by the public.)
An ASP.Net MVC 3 application with a model using SQL Server Express as the DB.
Successfully run on my Windows development machine.
(Following the MVC 3 Getting Started-tutorial)
Question
So far I managed to get Postgres to work with a "Dynamic Data Entities Web Application" but with an MVC 3 Web app I'm stuck on where/how to start. For the last mentioned MVC-3-Movie-Webapp I want to switch the DB from SQL Server Express to Postgres using NHibernate and Npgsql (NHibernate since Mono doesn't support Entity Framework).
When you look at the end of part 4 there's the simple MovieDBContext-code
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
and in the beginning of part 5, we autogenerate CRUD-stuff using Entity Framework by simply telling which Model to use.
(MoviesController.cs, Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml)
So I have that working with Entity Framework and SQL Server Express, but how would I achieve the same result by using NHibernate? (doesn't have to be with postgres immediately, sticking with SQL-Server as a first step would be fine) (Hopefully with similar simplicity, but getting the result itself would be great)
I found a lot of old stuff and how I would manually map things, but what would be a good-up to date standard way of achieving this with NHibernate for MVC 3?
(The closest thing I found was the source code mentioned in this thread, but it's 64 MB unzipped I got several "Projects not loaded successfully"-errors and the author said he uses MVC 2 so I think it's a little over my head for being a complete NHibernate noob.)
I think showing how this is done could be very useful for others as well, since the original tutorial is very easy to follow and is linked as the official starting point for MVC 3 app-development on http://www.asp.net/mvc ("Your First ASP.NET MVC App").
So I think this would be a great up to date example about how to use NHibernate with MVC 3.
Actually, those automated things haven't helpful enough in real world applications. We have to separate concerns and by using DataContext in UI Layer is not a good practice because that dependency will cause problems like lack of test-ability, violation of best practices. I think you need to have following things of your project
Separation of Concern (Layered Architecture - UI Layer, Servie Layer, Domain Layer, Infrastructure Layer)
Generic Repository and Unit of Work wrapping (Database functionalities, ORM - EF, NHibernate, etc
In your Service Layer process repositories and unit of work processings and expose Data Transfer objects or your domain objects (POCOs) to UI Layer
Use IOC to inject dependencies will help you to minimize dependencies
Create Unit test and Integration tests
Use Continuous Integration and Source control prefer (Distributed: Mercurial)
Useful References:
(Sharp Architecture) http://sharparchitecture.codeplex.com/
(IOC Container) http://www.castleproject.org/container/
(Generic repository) http://code.google.com/p/genericrepository/
NuGet is your friend. Here's a good example of using NuGet to automatically wire in your dependencies and configuration pretty much automatically.
Hope this helps.
Suggestion, don't get hung up on all the automatic stuff that the tutorials are showing you. Microsoft is just trying to show that you can easily get things started if you don't try to do anything unique.
Now for your situation. When you're making a controller, you're wanting to bind that controller with a type of model that you created somewhere. With nHibernate I'm thinking that you'll have manually created these POCO's and that you're using one of the many ways to map those POCO's through nHibernate to your database.
You won't be able to use the Entity Framework options because they're depending upon the features of the framework to provide information on the object, database, etc. Easiest things is to just make a controller that either gives you the options for CRUD or use an empty controller to build up your own ActionResults.
Hope this helps some and good luck with your project.