0

I do not have a database "Yet", and I've created my models which are annotated in a folder but when trying to create the initial migration using the command dnx ef migrations add Initial I gives me the error No DbContext was found.

I thought it would generate the DBContext from the annotations I added to my Models, My question is - Is there a command to generate the DBContext from my annotated models or do I have to write the DBContext manually when there is no database?

Bread
  • 423
  • 5
  • 16
  • 1
    You should add one file with definition of DBContext like `public class MyDBContext : DbContext { DbSet Users { get; set; } DbSet Orders { get; set; } ... }`. You can define multiple context for different databases in one program. You should use additional parameter to specify which dbcontext needed be created. You can download demo project from [the old answer](http://stackoverflow.com/a/34556712/315935). – Oleg Jan 30 '16 at 13:04
  • @Oleg Thanks a lot that was helpful – Bread Jan 30 '16 at 13:14
  • I'm glad if I could help you. You are welcome! – Oleg Jan 30 '16 at 13:17

1 Answers1

2

Always when I'm using Code First I have to manually create DBContext (and I think that it wouldn't create automatically any DbContext anyway). So you created your model ye? After that I create DbContext class (I'm always creating for this DAL folder) and in this class:

public class YourDBContextClassName : DbContext
    {
        public YourDBContextClassName () : base("YourDBContextClassName ") 
        {

        }

        public DbSet<YourModelName> YourName { get; set; }
        //other models
        //with YourName if you have for example Book Model then it could be something like this:
        public DbSet<Book> Books { get; set; }
    }

This base is from Web.config file and the name must match with name in connectionStrings

<connectionStrings>
    <add name="YourDBContextClassName " connectionString="Data Source=(localdb);Initial Catalog=YourCatalogDB;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
  </connectionStrings>

Of course connectionString can be diffrent in your case.

Münich
  • 343
  • 3
  • 13