我遵循了MVC 3中的教程,并执行了以下操作:
制作了4个类和一个DBClass:User
[具有] Website
的列表[具有a] Page
的列表[has a] Comment
的列表[每个标记的单词都是其自己的类]。
然后,我以这种方式制作了一个名为UserDataBaseDB
的类:
public partial class UserDataBaseDB : DbContext
{
public DbSet<User> Users { get; set; }
public UserDataBaseDB()
: base(@"UserDataBaseDB")
{
if (this.Database.Exists())
{
try
{
this.Database.CompatibleWithModel(false);
}
catch (InvalidOperationException)
{
this.Database.Delete();
}
}
if (!this.Database.Exists())
{
this.Database.Create();
Seed();
}
}
private void Seed()
{
var Mark = new User();
Mark.ID = 0;
Mark.MD5Pass = "4297f44b13955235245b2497399d7a93";
Mark.UserName = "Admin";
var Troll = new Comment();
Troll.CommentData = "Fake!";
Troll.Writer = Mark;
var Site = new Website();
Site.Name = "Admin Site";
Site.Pages.ElementAt(0).Data = "Awesome website!";
Site.Pages.ElementAt(0).Comments.Add(Troll);
Mark.Websites.Add(Site);
Users.Add(Mark);
}
public static UserDataBaseDB Create()
{
return new UserDataBaseDB();
}
public User FindUserByID(int id)
{
return (from item in this.Users
where item.ID == id
select item).SingleOrDefault();
}
然后我添加了
Controller
和View
,并导航到http://localhost:40636/Main
,然后看到以下消息:建立与SQL Server的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称正确,并且已将SQL Server配置为允许远程连接。 (提供者:SQL网络接口,错误:26-指定服务器/实例时出错)
Line 14: : base(@"UserDataBaseDB")
Line 15: {
Line 16: **if (this.Database.Exists())**
Line 17: {
Line 18: try
让标记线为红线。
我尝试重新安装Entity Framework,也尝试使用EFCodeFirst,尝试制作自己的
SqlDataBase
并为其提供连接字符串,但是没有任何效果。有人知道解决方案吗?谢谢!
PS:我在Win7 64位计算机上使用VS Ultimate SP1。
最佳答案
这可能是一个连接字符串问题,但是我确实看到您正在尝试播种信息并在构造函数中完全使用上下文,我强烈建议您不要这样做。
您可以实现OnModelCreating方法并在那里尝试您的初始化代码,甚至可以在应用程序启动时更好。似乎只是因为此时才开始初始化而被卡在构造函数中似乎并不对。
在上设置断点
如果(this.Database.Exists())
该行之后是否立即发生错误?如果是这样,请三遍检查您的连接字符串。您是否将代码包含在一个项目中,或者细分了?如果您恰好正在使用该设计,请确保在根Web项目的web.config中而不是在任何组件的app.config中检查连接字符串。
每次从代码优先更改等等时,是否都更改了连接字符串?代码优先的连接字符串是根据上下文类命名的,很简单:<add name="UserDataBaseDB" connectionString="Data Source=|DataDirectory|test.sdf" providerName="System.Data.SqlServerCe.4.0" /%gt;
那当然是使用SQLCe4。 SQL Server将是<add name="UserDataBaseDB" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=YourDbName;Integrated Security=True;Pooling=False" /%gt;
或app_Data中的数据库<add name="UserDataBaseDB" providerName="System.Data.SqlClient" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\YourDatabase.mdf;User Instance=true" /%gt;