我是一個新手,並試圖學習如何在C#中實現數據庫的代碼優先方法。我跟着this guide of Microsoft但我的代碼無法運行。 試圖修復它在互聯網上一整天,但無法找到任何解決方案,我的情況。我繼續前進,我非常需要你的幫助。SqlException是未處理的錯誤C#
你可以在教程中找到代碼,但爲了方便起見,你也可以在下面找到它。
它stucks在db.Blogs.Add(博客)線,它提供了以下錯誤:
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; }
}
}
下面是對現在的服務器資源管理器的情況:
下面是SQl服務器對象瀏覽器的情況。
以下是建議之後,我的app.config:
<?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>
什麼是完整的異常消息和'StackTrace'到底是什麼? –
代碼有什麼問題?例如,你看到什麼編譯時或執行時錯誤? – RoadWarrior
現在添加這些信息 –