-1

I'm a newbie and trying to learn how can I achieve Code-First Approach to the Database in C#. I followed this guide of Microsoft but my code is not able to run. Trying to fix it for a whole day on the internet but cannot find any solution to my case. Me to move on, I desperately need your help.

You can find to code in tutorial, however just for your convenience, you can find it below too.

It stucks in db.Blogs.Add(blog) line and it gives the following error:

SqlException was unhandled. Additional information Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace CodeFirstNewDatabaseSample
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                // Create and save a new Blog 
                Console.Write("Enter a name for a new Blog: ");
                var name = Console.ReadLine();

                var blog = new Blog { Name = name };
                db.Blogs.Add(blog);
                db.SaveChanges();

                // Display all Blogs from the database 
                var query = from b in db.Blogs
                            orderby b.Name
                            select b;

                Console.WriteLine("All blogs in the database:");
                foreach (var item in query)
                {
                    Console.WriteLine(item.Name);
                }

                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
    }

    public class Blog
    {
        public int BlogId { get; set; }
        public string Name { get; set; }

        public virtual List<Post> Posts { get; set; }
    }

    public class Post
    {
        public int PostId { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }

        public int BlogId { get; set; }
        public virtual Blog Blog { get; set; }
    }

    public class BloggingContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<Post> Posts { get; set; }
    }
}

Below is the Server Explorer's situation right now:

enter image description here

And below is the SQl Server Object Explorer's situation.

enter image description here

The following is my app.config after the suggestions:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="BloggingContextDb" connectionString="Data Source=|DataDirectory|BloggingContext.sdf" providerName="System.Data.SqlServerCe.4.0"/>
  </connectionStrings>
</configuration>
Kutay Demireren
  • 640
  • 1
  • 10
  • 25
  • 2
    What is the full exception message and `StackTrace` exactly? – Soner Gönül Feb 05 '16 at 11:21
  • What is the problem with the code? For example, what compile-time or execution-time error are you seeing? – HTTP 410 Feb 05 '16 at 11:23
  • Adding those information now – Kutay Demireren Feb 05 '16 at 11:23
  • Looks like your password or username for the database is not working. Do check if you are able to login to your database using the username and password you are using in code. Check you connection string. – Rahul Tripathi Feb 05 '16 at 11:28
  • I am not using any password or username. Does not it have to connect just my localdb? – Kutay Demireren Feb 05 '16 at 11:30
  • The problem is in your connectionstring. Add it to the question – Steve Feb 05 '16 at 11:32
  • There is no other code or something. The whole thing I have in the code is above you can see. It is because the guide doesn't require me to add any connection string. I am at the first step of the guide. This means the section "4. Reading & Writing Data" – Kutay Demireren Feb 05 '16 at 11:34
  • 1
    Your app.config contains the connection string used. This is missing or is wrong for your actual db. – Steve Feb 05 '16 at 11:37

2 Answers2

2

In this type of scenario, DbContext will try to create the database for you. Either in SQLExpress if that's installed locally (by default with VS2010), or in LocalDb if that's installed locally (by default with VS2012).

You can use the Server Explorer window in Visual Studio to look for the locally-installed instance of SQL Server. I suspect that there is no local installation, or the code is unable to access it for some reason (authentication, authorisation, etc).

This is what I see in VS2013 when using the SQL Server Server Object Explorer window. It looks like from your second screenshot that you do have LocalDb installed. Can you connect to it manually?

You may need to specify an explicit connection string that DbContext can use. That's normally done in app.config - see that link for creating the app.config file.

enter image description here

Community
  • 1
  • 1
HTTP 410
  • 17,300
  • 12
  • 76
  • 127
  • Where should I see the local installation? There are files shown in the server explorer, I will share in my answer. Please refer to the screenshot I added. – Kutay Demireren Feb 05 '16 at 11:43
  • Ah, you did want to me to refer SQL Server Object Explorer. That is also coming right away. – Kutay Demireren Feb 05 '16 at 11:45
  • Uploaded. Please refer again. The only difference between our explorer's looks like I have 2 databases. – Kutay Demireren Feb 05 '16 at 11:49
  • I found the web.config and app.config in the download packages of nuget. Do I have to change them – Kutay Demireren Feb 05 '16 at 11:59
  • No, you don't need nuget. I will edit my answer shortly to explain. – HTTP 410 Feb 05 '16 at 12:06
  • Okay as you suggested I came up with something similar to the link you shared, still cannot help me to work it. You can my find the app.config in my question. – Kutay Demireren Feb 05 '16 at 12:13
  • Thanks for your efforts I think it is the right solution but because I do not know much I could not figure it out. When I am done, hopefully, I will inform you – Kutay Demireren Feb 05 '16 at 14:02
  • Thanks to you and Steve, I am able to manage it. For those who will look for the answer, after this accepted answer please refer to the Steve's answer so that you can see the managed app.config. Again, thanks you a lot to show me the right path. – Kutay Demireren Feb 05 '16 at 15:08
  • 1
    @Kutay, apologies for not completing this, as I had to go visit family. Looks like Steve did a good finishing job. – HTTP 410 Feb 07 '16 at 11:56
2

I am not sure how do you end up with that app.config.
That config is not valid for use by EntityFramework ( as far as I know ) and uses an SDF file located in the BIN\DEBUG folder under your project folder.
By the way, the SDF files are files used by Sql Server Compact Edition, not by Sql Server Express or Sql Server LocalDb.

I have followed the same tutorial (just using Visual Studio 2015 instead) and the resulting app.config in my project is this one

<?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.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

The only problem (for me) is in the part where they talk about configuring Server Explorer to view the database file. I have to use (localdb)\mssqllocaldb as server name instead of the suggested (localdb)\v11.0
(Look at the Parameter key above in the app.config)

Now at step 4 of the tutorial I run the program and everything works as expected.

So I think you should change the content of the app.config with the above or repeat the tutorial from the beginning, taking care not to change anything. If the error persist I can only recommend to switch to Visual Studio 2015 Community Edition (it's free)

Steve
  • 213,761
  • 22
  • 232
  • 286
  • I will try it in an hour, when I try I will inform you. Thanks for your interest on me. – Kutay Demireren Feb 05 '16 at 14:01
  • Voila! I am so glad to you and RoadWarrior. Although the last hit to the goal came from you I think RoadWarrior led us to that way so I will up you both but I will accept his answer. But still I am so glad to you! Can I ask you that if I have to do repeat that app.config process for every project? Because the app.config is in the project, others will not able to see that app.config i guess. And can you explain a little, I would like to learn what you did there. Thanks a lot! – Kutay Demireren Feb 05 '16 at 15:07
  • That was pretty clear from the error message as I have said in my first comment. The strange thing is the app.config mess. I think that only if you retry the tutorial from the beginning you could know if this problem repeats itself – Steve Feb 05 '16 at 15:10
  • 1
    Yeah you are right actually you told me but I got hard times to understand. And okay I am going to retry again it was a simple step so will not take too long. – Kutay Demireren Feb 05 '16 at 15:14
  • Yeah it repeated the same error again as I guess. Is there any common file for app.config files that they refer to while the project is being created? – Kutay Demireren Feb 05 '16 at 15:19
  • 2
    @Steve, +1 for finishing this - I had to go visit family. – HTTP 410 Feb 07 '16 at 11:57