【发布时间】:2014-05-02 18:43:04
【问题描述】:
我正在尝试使用 EF Code First 方法创建数据库。我有一个DataAccessLayer 和一个DomainLayer,方式如下:
namespace DomainLayer
{
public class Lodging
{
public int LodgingId { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public bool IsResort { get; set; }
public Destination Destination { get; set; }
}
public class Destination
{
public int DestinationId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Description { get; set; }
public byte[] Photo { get; set; }
public List<Lodging> Lodgings { get; set; }
}
}
using System.Data.Entity;
using DomainLayer;
namespace DataAccessLayer
{
public class BreakAwayContext : DbContext
{
public DbSet<Destination> Destinations { get; set; }
public DbSet<Lodging> Lodgings { get; set; }
}
}
我创建了一个控制台应用程序以通过以下方式测试该应用程序:
namespace BreakAwayConsole
{
public class Program
{
public static void Main(string[] args)
{
InsertDestination();
}
private static void InsertDestination()
{
var destination = new Destination
{
Country = "Indonesia",
Description = "EcoTourism at its best in exquisite Bali",
Name = "Bali"
};
using (var context = new BreakAwayContext())
{
context.Destinations.Add(destination);
context.SaveChanges();
}
}
}
}
但是当我运行该应用程序时,它给了我以下错误:
例外:
An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct.
消息:
The provider did not return a string ProviderManifestToken.
内部异常:
A network-related or instance-specific error occurred while a connection to SQL Server is established. Server not found or was not accessible this. 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 or Instance Specified)
我的机器上也安装了 SQL Server 2005。但根据我正在阅读的书:
Code First 使用它在 Destination 和 Lodging 类中发现的信息来确定模型并推断持久化这些类的数据库的模式。由于我们没有提供连接字符串信息,因此它使用其默认约定,即在本地 SQL Server Express 实例 (localhost\SQLEXPRESS) 中查找与上下文类 DataAccess.BreakAwayContext 的完全限定名称匹配的数据库。没有找到,Code First 创建数据库,然后使用它按照约定发现的模型来构建数据库的表和列。
编辑
我的app.config 文件位于BreakAwayConsole 项目中,并且包含以下几行:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
感谢任何帮助。
【问题讨论】:
-
我这里猜测一下,你的datalayer项目的app.config中有连接字符串信息,但是你的控制台应用的app.config中没有连接字符串信息.您可以将数据层 app.config 中的连接字符串信息复制并粘贴到控制台 app.config 中,您应该已准备就绪。
-
@jrhutch 我的连接字符串在我的控制台应用程序项目中,而不是在数据层中
-
连接字符串中的服务器名称是否与您在 SQL Management Studio 中看到的实例名称匹配?
-
App.config中connectionString的名称是什么?应该是 BreakAwayContext
标签: c# database entity-framework ef-code-first