I just have created my first codefirst model and want to enable migrations.
This is part of my Model code:
namespace Layers.Data_Access_Layer.CodeFirst.Entities
{
public partial class MyModel : DbContext
{
public MyModel()
: base("name =CodeFirstModel")
{
}
public virtual DbSet<tblBaseInfo> tblBaseInfo { get; set; }
.
.
.
}
}
I just wrote the following instruction :
Enable-Migrations -CodeFirstModel Layers.Data_Access_Layer.CodeFirst.Entities
and unfortunately I received the following error:
Enable-Migrations: A positional parameter cannot be found that accepts
argument 'CodeFirstModel'. At line:1 char:1
+ Enable-Migrations CodeFirstModel Layers.Data_Access_Layer.CodeFi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Enable-Migrations], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Enable-Migrations
Please help me to handle my error with enabling migration.
I have an extra question: when I enable migrations in my project, does it automatically add a table to SQL server (dbo.__migrationHistory) ??
Related
I want my windows application to warn that there are migrations to run but to give the user the option to continue without running them.
At the moment I have code first projects with no migrations that access the database
However in the project where I do the database migrations I must either allow the migration to run or delete the migration and undo my changes to the model.
For the configuration I have
internal sealed class Configuration : DbMigrationsConfiguration<MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
For the migration check I have
using (var db = new MyDbContext())
{
var compatible = db.Database.CompatibleWithModel(false);
if (!compatible)
{
compatible= RunMigrations(db);
}
return compatible;
}
If I don't allow the migration then I get the model backing error when I try to access data
var n = db.mytable.count() // will error
If I comment out the Configuration class and code that calls it I can run the program without error.
The trick is to create a new dbContext inheriting from the usual
public class MigrationDbContext : MyDbContext
{
}
Then the configuration class should use the MigrationDContext
internal sealed class Configuration : DbMigrationsConfiguration<MigrationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
}
and the migration check should use the MigrationDbContext
I know there are N no of solutions with same title and after 3 days and useless running through them all I have to post it here.
I've an UserDetailDAC.cs like this:-
public UserDetails ValidateUserAdmin(string Usrname, string pwd)
{
using (var db = new HostelManagementContext())
{
//IEnumerable<UserDetails> linq;
//string query = "SELECT* FROM UserDetails WHERE UserName ='" + Usrname + "' COLLATE SQL_Latin1_General_CP1_CS_AS AND UserPwd = '" + pwd + "' COLLATE SQL_Latin1_General_CP1_CS_AS";
//linq = db.Database.SqlQuery<UserDetails>(query);
//return linq.FirstOrDefault();
return db.Set<UserDetails>().Where(x => x.UserName == Usrname && x.UserPwd == pwd).FirstOrDefault();
}
}
and my HostelManagementContext.cs is like this :-
public HostelManagementContext() : base("ConnectionString")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<HostelManagementContext, HostelModel.Migrations.Configuration>("ConnectionString"));
//Database.SetInitializer<HostelManagementContext>(new DropCreateDatabaseIfModelChanges<HostelManagementContext>());
}
public DbSet<CandidateHostelBookingMapping> CandidateHostelBookingMappings { get; set; }
public DbSet<UserDetails> UserDetails { get; set; }
Now when I try to run this it gives me below error:-
Cannot find the object "CandidateHostelBookingMappings" because it does not exist or you do not have permissions.
This is Entity Framework Code first approach. Please feel free to ask any further details
//Are you use Migration for creating database and table using package manager console ?
enable-migrations -ContextTypeName HostelManagementContext
add-migration -ConfigurationTypeName -----
update-database -ProjectName
I'm working on an MVC site that is using ASP.Net Identity for the log in piece.
There is a user table where the pk is an FK for another table (table 2). Because of this, the user cannot be deleted. As well, there are reports that are generated from table 2. This report displays the data from table 2 as long as the user name that generated the data. Another reason why deleting the user information should not be done.
So instead of deleting the user I thought I would add a column to the user table called "Deleted". It uses a bit datatype.
The column was added to my local copy of the database using code-first migrations. When the user logs on, this value is checked in this column is checked (0 = not deleted; 1 = deleted).
Everything was working great on my local machine. I had no errors, code ran fine. I was able to log in with any user. I then deployed to our test server and added the "Deleted" column to the table on the test SQL server using a script.
When I went to log in, with any user, I couldn't. I kept getting the "Error logging in. Please re-enter credentials and try again" even though my credentials were correct.
I deleted the files on the server and deployed again. Same thing.
I backed out all of my changes and deployed again and was able to log in.
So, I started adding things a piece at a time:
I ran the script to add a Deleted column with a bit datatype and set
to not null on our test SQL server
Tested logging in and was able to
Added public bool Deleted {get; set;} to my BL Entity and deployed to
test
Tried logging in and failed
Removed the Deleted bool and re-deployed
Was able to log in
I'm not understanding why this addition is causing issues. "Deleted" columns are used in other tables in the application and have not caused any issues. And because it's working fine when I run it locally I'm having a hard time determining what the issue is.
Here is my BL Entity:
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
namespace BlahBlah.BusinessLogic.Entities
{
public class User : IdentityUser
{
public User() : base() { }
public User(string username) : base(username) { }
public Guid CompanyId { get; set; }
public Company Company { get; set; }
public bool PrimaryAccount { get; set; }
public Guid DefaultCompanyId { get; set; }
public ICollection<Transaction> Transactions { get; set; }
// public bool Deleted { get; set; }
}
}
Here is a piece of my user.js code:
...
$http(call)
.success(function (data) {
userData.isAuthenticated = true;
userData.username = data.userName;
userData.role = data.role;
userData.bearerToken = data.access_token;
userData.expirationDate = new Date(data['.expires']);
setHttpAuthHeader();
if (typeof successCallback === 'function') {
successCallback();
}
})
.error(function (data) {
if (typeof errorCallback === 'function') {
if (data.error_description) {
errorCallback(data.error_description);
}
else {
errorCallback('Unable to contact server; please, try again later.');
}
}
});
};
...
Here is a piece of my login.js code:
...
function login(common, $location, config) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
vm.title = 'Login';
vm.credentials = {
username: '',
password: ''
};
vm.hideError = true;
vm.errorMessage = 'xx.';
vm.login = function login() {
vm.hideError = true;
common.$broadcast(config.events.spinnerToggle, { show: true });
common.user.authenticate(vm.credentials.username, vm.credentials.password, onSuccessfullLogin, onFailedLogin);
};
...
function onFailedLogin(error) {
common.$broadcast(config.events.spinnerToggle, { show: false });
console.log('error ' + error);
vm.hideError = false;
}
...
Any ideas as to what is going on or how I can find out what is going on? Thanks for your time!
UPDATE
I shouldn't have gotten too excited. After performing some testing in the application I thought I would test the reports. Everything was working beautifully up until then. When I viewed a report I got the following error:
The model backing the 'BabDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database
The reports are using SSRS. If I ran the script to create the column AND update the _Migrations table I'm not understanding why I'm getting this error. The stack trace points to the last line. I've read suggestions but where I need to add some code to the OnModelCreating method but I'm not sure if that's the way to go. There have been other deploys done by others prior to me so I'm missing something.
public class AbaDbContext : IdentityDbContext<User>, IDbContext
{
public const int UnknownCTId = 1;
private IEncryptionService _encryptionService;
private static Dictionary<Guid, string> _cipherCache = new Dictionary<Guid,string>();
public BabDbContext()
: base("BabDbContext")
{
((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += new ObjectMaterializedEventHandler(ObjectMaterialized);
It looks like your context is trying to run migrations on the production server and is failing due to either insufficient permissions or that the Deleted column already exists. Your options are:
Run your production migrations by creating a script. You can do this by running the following command:
Update-Database -Script
This will create a SQL script that yuo can run against your database to create the column and, critically, insert a row into the __MigrationHistory table that tells EF that it doesn't need to run migrations again.
Create a context initialiser that effectively disables migrations. Add a class that inherits from NullDatabaseInitializer<T>:
public class DisableMigrations : NullDatabaseInitializer<YourContext>
{
}
And in your production web.config:
<entityFramework>
<contexts>
<context type="YourNamespace.Domain.YourContext, YourNamespace.Domain">
<databaseInitializer
type="YourNamespace.Domain.DisableMigrations, YourNamespace.Domain"/>
</context>
</contexts>
</entityFramework>
I have a rule where I have a declaration returns
tablename
returns [String fieldString, TableObj obj]
TableObj is a custom class that I declare in the same g4 file
class TableObj {
public String realName;
public String aliasName;
public List<String> fields;
public List<Relation> relations;
public TableObj(){
fields = new ArrayList<String>();
relations = new ArrayList<Relation>();
}
}
but when I have to try access a field of obj using $obj.field the generated code is:
_localCtx.field
instead of
_localCtx.obj.field
How do I do to obtain the second form instead of the first?
If it will need or it will help follows a snippet of my rule
tablename
returns [String fieldString, TableObj obj]
:
(tablePrefix=ID {
$obj.aliasName = $tablePrefix.text;
System.out.println( "Alias = " + $tablePrefix.text + " " + $obj.aliasName );
}
;
This is a bug in ANTLR that you should report to the project issue tracker:
https://github.com/antlr/antlr4/issues
I have a windows service that depends on a 3:rd party API
The API is already installed in the GAC on the client computer
There are several versions of the API (1.0.0.0, 1.1.0.0 etc)
My service works with all versions of the API
I use a bindingRedirect tag in the app.config file which works fine when running the service.
Problem is that the app.config file is not used when running InstallUtil so I get a binding exception when registering the service.
Currently I use "sc create" to manually register the service but is there a better way?
(without editing machine.config etc)
I just ran in to this, the only solution I could find is from https://connect.microsoft.com/VisualStudio/feedback/details/525564/installutil-exe-does-not-honor-app-config-especially-binding-information:
As a workaround, you might be able to make this work by modifying the InstallUtil.exe.config file to contain the binding information. The InstallUtil.exe.config is installed to %WinDir%\Microsoft.NET\Framework\\InstallUtil.exe.config where is the version of framework you're using.
I came up with another workaround to install service with binding redirects. As I have a lot of services, this is what I decided to go after.
Change Windows installer to Console app and implement functionality to self install (using command line and ManagedInstallerClass.InstallHelper).
Implement an installer class capable of executing command line in a completely separate assembly, for example CommandLineInstaller.DLL. CommandLineInstaller.DLL shall implement methods Install/Uninstall/Rollback identically - execute a command line with parameters such as:
FileName, WorkingDirectory, Args, WindowStyle.
Modify setup project to deploy both 1) service and b) CommandLineInstaller.DLL
Modify setup project custom actions: instead of running actions of service, run actions of CommandLineInstaller.DLL. CustomActionData property for Install action will look like:
/FileName="[TARGETDIR]MyService.exe" /Args="/install" WindowStyle="Hidden"
Action configuration:
Install: myservice /install
Rollback: myservice /uninstall
Uninstall: myservice /uninstall
No need to write Commit, AFAIK.
Now, setup project will execute CommandLineInstaller.DLL installer in its own process. And then CommandLineInstaller.DLL will in turn launch MyService.exe in its own process with bloody binding redirects as they should be.
PS MyService.exe can use exit code mechanism to inform installer about failures and I highly recommend checking them from CommandLineInstaller.
Hopefully it's a good enough outline.
PS Be mindful of TARGETDIR needs to have a slash when passed by itself to directories:
/WorkDir="[TARGETDIR]\"
Example of Install CustomActionData:
/FileName="[TARGETDIR]\MyService.exe" /Args="/install" /WorkingDir="[TARGETDIR]\" /ValidExitCode="0" /WindowStyle="Normal"
Some code:
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
namespace QT.Install
{
[RunInstaller(true)]
public partial class ExecuteCommandInstaller : System.Configuration.Install.Installer
{
public class CommandArgs
{
public string FileName { get; set; }
public string WorkingDir { get; set; }
public string Args { get; set; }
public string ValidExitCode { get; set; }
public ProcessWindowStyle WindowStyle { get; set; }
}
public ExecuteCommandInstaller()
{
InitializeComponent();
}
public override void Install(IDictionary stateSaver)
{
base.Install(stateSaver);
ExecuteCommand(stateSaver);
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
ExecuteCommand(savedState);
}
public override void Uninstall(IDictionary savedState)
{
base.Uninstall(savedState);
ExecuteCommand(savedState);
}
public override void Rollback(IDictionary savedState)
{
base.Rollback(savedState);
ExecuteCommand(savedState);
}
private void ExecuteCommand(IDictionary stateSaver)
{
CommandArgs commandArgs = new CommandArgs()
{
FileName = StripDoubleSlash(Context.Parameters["FileName"] ?? ""),
WorkingDir = StripDoubleSlash(Context.Parameters["WorkingDir"] ?? ""),
Args = Context.Parameters["Args"] ?? "",
ValidExitCode = Context.Parameters["ValidExitCode"] ?? "*"
};
try
{
commandArgs.WindowStyle = (ProcessWindowStyle)Enum.Parse(typeof(ProcessWindowStyle), Context.Parameters["WindowStyle"] ?? "Hidden");
}
catch (Exception err)
{
throw new Exception($"Invalid WindowStyle parameter value: {Context.Parameters["WindowStyle"]}", err);
}
InternalExecuteCommand(commandArgs);
}
private void InternalExecuteCommand(CommandArgs commandArgs)
{
if (string.IsNullOrEmpty(commandArgs.FileName))
throw new Exception("FileName is not specified.");
System.Diagnostics.ProcessStartInfo startInfo = new ProcessStartInfo(commandArgs.FileName, commandArgs.Args);
if (!string.IsNullOrEmpty(commandArgs.WorkingDir))
startInfo.WorkingDirectory = commandArgs.WorkingDir;
startInfo.WindowStyle = commandArgs.WindowStyle;
using (var process = Process.Start(startInfo))
{
process.WaitForExit();
if (commandArgs.ValidExitCode != "*")
{
if (process.ExitCode.ToString() != commandArgs.ValidExitCode)
throw new Exception($"Executing {commandArgs.FileName} {commandArgs.Args} returned exit code {process.ExitCode}. Expected exit code is: {commandArgs.ValidExitCode}.");
}
}
}
private static string StripDoubleSlash(string value)
{
return value.Replace("\\\\", "\\");
}
}
}