0

Just getting started learning EF and databases in general, so I've been following this short tutorial: http://www.entityframeworktutorial.net/code-first/simple-code-first-example.aspx

I made it work with his example, but when I try with my own classes and such, no database is created (or at least I can't find it anywhere in the object explorer), and I hope you could tell me why?

I know that I have not declared a connection string in the base() part of the context class, but in the example from the tutorial he doesn't either, so that shouldn't be the problem I guess? Thanks in advance :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShopEntity
{
    class Product
    {
        public int ProductId { get; set; }
        public int Price { get; set; }
        public string ProductName { get; set; }


    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShopEntity
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            using (var ctx = new ShopContext())
            {
                User adminUser = new User()
                {
                    Address = "Skejby Vænge 96A",
                    EMailAddress = "[email protected]",
                    IsAdmin = 1,
                    PassWord = "12345678",
                    UserName = "Anders1234"
                };
                //Product Apple = new Product() { Price = 2, ProductName = "Apple" };
                //Product Melon = new Product() { Price = 10, ProductName = "Melon" };
                //Product Beef = new Product() { Price = 40, ProductName = "Beef" };
                ctx.Users.Add(adminUser);
                //ctx.Products.Add(Apple);
                //ctx.Products.Add(Melon);
                //ctx.Products.Add(Beef);
                ctx.SaveChanges();

            }




                Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShopEntity
{
    class ShopContext: DbContext
    {
        public ShopContext() : base()
        {

        }

        public DbSet<User> Users { get; set; }

        public DbSet<Product> Products { get; set; }


    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShopEntity
{
    class User
    {

        public int UserId { get; set; }

        [MaxLength(20)]
        public string UserName { get; set; }

        [MaxLength(20)]
        public string PassWord { get; set; }
        public string EMailAddress { get; set; }

        [MaxLength(50)]
        public string Address { get; set; }
        public byte IsAdmin { get; set; }

    }
}

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>
3
  • 2
    Is your connection string defined in your app.config? Commented Feb 14, 2017 at 19:40
  • Two sec, gonna add the app.config to the post - should be there now :) Commented Feb 14, 2017 at 19:41
  • 1
    see my answer.. there are a few things you're going to need to do Commented Feb 14, 2017 at 19:46

3 Answers 3

1

I'm not sure why in the example he does not pass the connection string into the base constructor but this is needed to tell DbContext what database to connect to. The following is a link that is in the example you are using.

http://www.entityframeworktutorial.net/EntityFramework4.3/dbcontext-vs-objectcontext.aspx

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

2 Comments

I tried to add it this way: public ShopContext() : base("name=ShopDBEntity") But now I get an exception: An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll Additional information: No connection string named 'ShopDBEntity' could be found in the application config file.
see my answer for the complete solution
1

It doesn't look like you have a connection string defined anywhere in your app. You'll need to define the connection in the app.config, then reference it in your context class.

app.config

You will need to modify the connection string to meet your needs based on the DB name and authentication options.

   <configuration>
     <connectionStrings>
      <add name="myConnection" connectionString="SERVER=myServer;Integrated Security=SSPI;Initial Catalog=myDB"/>
     </connectionString>
    </configuration>

DB Context

The name of the connection in your app.config needs to be passed into the base DbContext` class definition.

class ShopContext: DbContext
        {
            public ShopContext() : base("myConnection")
            {

            }

            public DbSet<User> Users { get; set; }
            public DbSet<Product> Products { get; set; }

        }

4 Comments

Thanks, that clears up a few things - still confused by how it managed to create a database when I did it with his example though, but that's irrelevant I guess :) At the moment I'm not connecting to any server, just using the local database, so what should I write in the SERVER=myServer part of your answer?
if you're using sql server local db, the server will be: (LocalDB)\MSSQLLocalDB or (LocalDB)\v<version>.0 (if running an older version)
Thanks a lot - unfortunately I'm getting hit by another exception, perhaps I've messed something up with all my past tries of getting the database created.. An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll Additional information: Typeinitialiseringsfunktionen for 'System.Data.Entity.Internal.AppConfig' threw an exception.
In cases like this, An Entity Framework factory routine puts the database in a default location, namely your Windows profile directory/folder. So it should be possible to use this without a custom connection string; but as you mentioned, it is better to declare a spesific string. Bewere though of folder ACL issues.
1

The database is created alright, but the dumbest thing no one never mention in cases like this is that the database is created in your Windows profile directory/folder. This example uses the default location, in some sort of Entity Framework default and invisible connectionstring (a factory function). Take a peek into c:\users[yourmachineloginname] and observe that there's a database prefixed ConsoleApplication, or with the prefix ShopEntity in your case. In order to put this database somewhere else, you need to create a spesific connection string.

To make a spesific connection string, do this:

0) Remove the database file created in your Windows profile folder

1) In your project folder, make a folder named App_Data

2) put this connection string into the app.config file:

<connectionStrings>
    <add name="myConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFileName=C:\projects\sabemos\ConsoleApplication1\ConsoleApplication1\App_Data\DatabaseFileName.mdf;Integrated Security=True;MultipleActiveResultSets=True" />
  </connectionStrings>

4) Remember to change the path (c:\projects...) in the connection string to the one that leads to YOUR database file

5) Ensure the connectionstring name corresponds to the name you use in your DbContext base initialisation

By now you should have the database pop up in the App_Data folder within your project folder

3 Comments

I can't actually find this one, but I can see the one I made when I used the example from the tutorial - but thanks anyway!
Where did you find the database then?
So far I can't find anywhere that the database from this project was created, I can only find the one that was created when I followed his tutorial and created the School database, and that was located where you said :)

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.