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:
And below is the SQl Server Object Explorer's situation.
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>