0

I'm currently creating a Windows Forms Application. I require a local database and have opted to use the code-first approach with the Entity Framework in order to build it. I have not worked with a database with C# before and I am struggling to set one up with the entity framework.

I currently have two classes: Ingredient, and Recipe. Both contain POCOs. From what I can gather, the entity framework should create a local database, making these classes tables. However a database is not being created.

Could anyone shed some light on what I am doing wrong? I apologise if my question is too broad.

Thank you for your time.

Ingredient Class:

    public class Ingredient
    {
        public int IngredientID { get; set; }
        public string IngredientName { get; set; }
        public string IngredientDescription { get; set; }
        public virtual Recipe Recipe { get; set; }
    }

Recipe Class:

public class Recipe
{
    public int RecipeID { get; set; }
    public string RecipeName { get; set; }
    public string RecpeDescription { get; set; }

    public virtual List<Ingredient> Ingredients { get; set; }

    public Recipe()
    {
        this.Ingredients = new List<Ingredient>();
    }
}

DbContext Class

class RecipeContext : DbContext
{
        public DbSet<Recipe> Recipes { get; set; }
        public DbSet<Ingredient> Ingredients { get; set; }
}
7
  • could you post your DbContext class, your connection string in the app.config, and your POCO classes? Commented Aug 29, 2015 at 15:52
  • how does DbContext constructor look like? and the connection string? Commented Aug 29, 2015 at 16:03
  • @DevilSuichiro I have added the dbcontext class and POCO classes, but I haven't written a specific connection string in app.config because I don't know how to write a connection string for a local database. For example, a C# service-based database (.mdf). I have experience working with SQL through PHP. I'm trying to avoid setting up a specific SQL database as those who download the finished application will need to have immediate access to a database - without having to setup one up of their own. Thank you for your time. Commented Aug 29, 2015 at 16:04
  • I haven't written a constructor for DbContext.. I'll do that now Commented Aug 29, 2015 at 16:06
  • without a connection string, EF will use SQL Server to localdb. for a context targeting a local mdf, you could use the overload of DbContext constructor like the following: Public RecipeContext() :base(new SqlCeConnection("Data Source=(path)"), true){} I think this code would work. note that the database will only be created when it is actually accessed by the context. Commented Aug 29, 2015 at 16:12

2 Answers 2

3

EF is quite flexible with these things. Get acquainted with the Nuget Package Manager Console (it is from there that you'll interact with Entity Framework DB generation routines). Following these steps you should be good to go:

  1. Add a connection string to your start up application. An example is the following:

    <configuration> <connectionStrings> <add name="Local" connectionString= "Data Source=.;Initial Catalog=NAME;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> </configuration>

  2. Create a Context class that inherits DbContex;

  3. Add the following constructor to you Context class:

    public Context() : base("Local") {}

  4. Add DbSet properties to your Context class (so EF can track them down);

  5. Go to the Package Manager Console, select the project that holds the DbContext class, and type the following:

    Enable-Migrations

  6. On the same console type:

    Add-Migration Initial

  7. Again in the same console:

    Update-Database

This should create a database with the name you have set in the connection string.

Hope this helps!

Cheers!

Sign up to request clarification or add additional context in comments.

Comments

0

You need a connection string and one of database initializers that create a database if it doesn't exists.

public class RecipeContext : DbContext
{ 
     // the default constructor
     public RecipeContext()  : base() { }

     // this one lets you pass a connection string
     public RecipeContext( string connectionString ) : base( connectionString ) { }

     ...

Then, at the very beginning of your app set the initializer:

  Database.SetInitializer<RecipeContext>(new CreateDatabaseIfNotExists<RecipeContext>());

And finally, just try to connect to your database, with a valid connection string:

 // local database connection string has to point to the local db server
 string cs = "server=(localdb)/v11.0;database=anewdatabase;integrated security=true";

 using ( var ctx = new RecipeContext( cs ) )
 {
    // any database operation will first trigger the initializer 
    // which initializes the database once per app domain

    // in case of the CreateDatabaseIfNotExists
    // a new, empty database matching your model is created
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.