Click here to Skip to main content
14,735,400 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am new to Code First migration. When i try to migrate , "System.NullReferenceException " exception has showed in Package Manager Console.

this is my DbContext class
namespace App.DataAccess
{
    public class StudentDb : DbContext
    {
        public StudentDb() : base(ConfigurationManager.ConnectionStrings["StudentDb"].ConnectionString)
        {
        }

        public StudentDb(string connectionString) : base(connectionString)
        {
        }

        public DbSet<Student> Student { get; set; }
       

        public virtual IDbSet<T> DbSet<T>() where T : class
        {
            return Set<T>();
        }

        public virtual void Commit()
        {
            base.SaveChanges();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            Database.SetInitializer<StudentDb>(null);
        }
    }

    internal class Initialiser : DropCreateDatabaseAlways<StudentDb>
    {
        protected override void Seed(StudentDb context)
        {
            context.SaveChanges();
        }
    }

    
}




this is the exception as it shows
PM> add-migration ss
System.NullReferenceException: Object reference not set to an instance of an object.
at App.DataAccess.StudentDb..ctor() in d:\TestMVC\StudentApp\App.DataAccess\StudentDb.cs:line 14
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Data.Entity.Infrastructure.DbContextInfo.CreateInstance()
at System.Data.Entity.Infrastructure.DbContextInfo..ctor(Type contextType, DbProviderInfo modelProviderInfo, AppConfig config, DbConnectionInfo connectionInfo, Func`1 resolver)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Object reference not set to an instance of an object.
PM>


Any help?
Posted
Updated 16-Jul-15 5:43am
v3
Comments
[no name] 16-Jul-15 10:29am
   
Any help... with what? Debug your code, find the object that is null, stop trying to use object that is null.

1 solution

You did not show where the exception with the message "Object reference not set to an instance of an object" is thrown.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object".

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx,
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx.

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx.

Good luck,
—SA
   
Comments
Prabhani Panamulla 16-Jul-15 12:12pm
   
public StudentDb() : base(ConfigurationManager.ConnectionStrings["StudentDb"].ConnectionString)
{
}
this is the place it has occurred. the thing is i can't debug because, the exeception is occured when i run a command in package manager console which is "add-migration student"
Sergey Alexandrovich Kryukov 16-Jul-15 12:26pm
   
Most likely, ConfigurationManager.ConnectionStrings["StudentDb"] returns null. Just use my directions.
Will you accept my answer formally? This is all you need.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900