我已经按照MVC 3中的教程进行了操作,并完成了以下操作:
制作了4个班级和一个DBClass:
User
[有一个] Website
的列表[有一个] Page
的列表[有一个] 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 64bit机器上使用VS Ultimate SP1。
答案 0 :(得分:3)
这可能是一个连接字符串问题,但我确实看到你正在尝试播种信息并在构造函数中完全使用上下文,我强烈建议你不要这样做。 您可以实现OnModelCreating方法并在那里尝试初始化代码,甚至可以在应用程序启动时更好。由于初始化刚刚开始,所以它似乎没有被卡在构造函数中。
在
上设置断点if (this.Database.Exists())
错误是在该行之后立即发生的吗?如果是这样,请检查连接字符串。您是将代码放在一个项目中还是已经破解了?确保您正在检查根网站项目的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;