我使用“Code First”O'Reily 书中的 CustomConnectionFactory 和 PromptForDropCreateDatabaseWhenModelChages “方式”创建了一个 MDF 文件,该文件已创建,但无法从 VS 或 SSMS 访问。我可以看到通过在 VS 服务器资源管理器中扩展树视图创建的数据库表和参数,但在“显示数据”上显示错误:“找不到指定的模块。(来自 HRESULT 的异常:0x8007007E) ”。我查看了这个错误,似乎服务器权限有问题,但是将 SSMS 设置为最高权限(系统管理员、所有者等)并没有帮助。我在想文件本身可能存在权限问题。提前感谢您的帮助。
这是代码:
应用程序.xaml.cs:
protected override void OnStartup(StartupEventArgs e)
{
AppDomain.CurrentDomain.SetData("DataDirectory", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ""));
Database.DefaultConnectionFactory = new CustomConnectionFactory();
Database.SetInitializer(new PromptForDropCreateDatabaseWhenModelChages<AppEntities>());
using (var context = new AppEntities())
{
context.Clicks.Add(new MouseClick
{
DateTimeCreated = DateTime.Now,
DateTimeModified = DateTime.Now,
Id = 1,
IsActive = true,
});
}
var mainView = new MainView
{
DataContext = new ViewModelMain(new AppEntities())
};
mainView.Show();
}
CustomConnectionFactory.cs:
class CustomConnectionFactory : IDbConnectionFactory
{
public DbConnection CreateConnection(string nameOrConnectionString)
{
var name = nameOrConnectionString.Split('.').Last().Replace("Entities", string.Empty);
var builder = new SqlConnectionStringBuilder
{
DataSource = @".\SQLEXPRESS",
AttachDBFilename = @"|DataDirectory|\App.mdf",
InitialCatalog = name,
IntegratedSecurity = true,
MultipleActiveResultSets = true,
UserInstance = true
};
return new SqlConnection(builder.ToString());
}
}
PromptForDropCreateDatabaseWhenModelChanges.cs:
public class PromptForDropCreateDatabaseWhenModelChages<TContext> : IDatabaseInitializer<TContext> where TContext : DbContext
{
public void InitializeDatabase(TContext context)
{
var exists = context.Database.Exists();
if (exists && context.Database.CompatibleWithModel(true))
{
return;
}
if (exists && context.Database.CompatibleWithModel(false))
{
context.Database.Delete();
}
context.Database.Create();
}
}