C# 创建CompactSql数据库并将其连接字符串动态添加到实体框架
我在c#WinForms、4.8.NET框架和实体6中工作 经过更多的研究,我发现了一些对我有帮助的东西: 1-将此添加到app.config:C# 创建CompactSql数据库并将其连接字符串动态添加到实体框架,c#,winforms,entity-framework-6,C#,Winforms,Entity Framework 6,我在c#WinForms、4.8.NET框架和实体6中工作 经过更多的研究,我发现了一些对我有帮助的东西: 1-将此添加到app.config: <connectionStrings> <add name="DatabaseEntities" connectionString="data source=%APPDATA%\writerapp.sdf, Password = 'writerapp'" providerName="System.Data
<connectionStrings>
<add name="DatabaseEntities"
connectionString="data source=%APPDATA%\writerapp.sdf, Password = 'writerapp'"
providerName="System.Data.SqlServerCe.4.0"/>
</connectionStrings>
3-将我的DbContext更改为:
public class WriterAppContext : DbContext
{
public WriterAppContext() : base(GetConnectionString()) { }
private static string GetConnectionString()
{
if (!string.IsNullOrEmpty(Settings.Default.LocalConString)
&& File.Exists(Settings.Default.LocalDbPath))
return Settings.Default.LocalConString;
else throw new NotImplementedException();
}
public DbSet<NotificationHandler> Notifications { get; set; }
}
公共类WriterAppContext:DbContext
{
public WriterAppContext():基(GetConnectionString()){}
私有静态字符串GetConnectionString()
{
如果(!string.IsNullOrEmpty(Settings.Default.LocalConString)
&&File.Exists(Settings.Default.LocalDbPath))
返回Settings.Default.LocalConString;
否则抛出新的NotImplementedException();
}
公共数据库集通知{get;set;}
}
感谢:
但我有一个错误:
System.ArgumentException:“初始化的格式不符合索引0的指定。”
表示:初始化链的格式不符合从索引0开始的规范
所以我不知道哪里出了问题?我终于发现了我的问题: 密码不要求输入密码
public class WriterAppContext : DbContext
{
public WriterAppContext() : base(GetConnectionString()) { }
private static string GetConnectionString()
{
if (!string.IsNullOrEmpty(Settings.Default.LocalConString)
&& File.Exists(Settings.Default.LocalDbPath))
return Settings.Default.LocalConString;
else throw new NotImplementedException();
}
public DbSet<NotificationHandler> Notifications { get; set; }
}
var strCount = ("; Password = writerapp").Length;
var strCount2 = ("data source=").Length;
var _conStr = System.Configuration.ConfigurationManager.ConnectionStrings["DatabaseEntities"].ConnectionString;
var _conString = _conStr.Replace("%APPDATA%", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
var _cleanPath = _conString.Remove(0, strCount2);
var _trimToFile = _cleanPath.Remove(_cleanPath.Length - strCount, strCount);