天道酬勤,学无止境

How to define DataDirectory for ConnectionString in console application to work with EntityFramework Code First Migrations

I try to set location MyProject\App_Data\Cos.mdf for the database in App.config:

 <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\Cos.mdf;Initial Catalog=Cos;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

In Program.cs I wrote:

 static void Main(string[] args) {

        string relative = @"..\..\App_Data\Cos.mdf";
        string absolute = Path.GetFullPath(relative);

        AppDomain.CurrentDomain.SetData("DataDirectory", absolute); 
        Console.WriteLine(absolute);
        Console.ReadKey();
 }

The displayed path is(I paste it to show that I didn't make a mistake):

enter image description here

but then when I type in Package Manager Console enable-migrations change AutomaticMigrations to true, then type update-database I get error:

Cannot attach the file 'C:\Users\s8359_000\Documents\Visual Studio 2013\Projects\Projekt5 — kopia\Projekt5\bin\Debug\Cos.mdf' as database 'Cos'.

Why does .NET tries to create my database in Debug directory?! I went through 15 subjects on StackOverflow on this topic and it looks like everybody just duplicates the answers which don't work.

EDIT AFTER ANSWER OF SRUTZKY Yes you are right there is error. I tried few more combination after your answer, unfortunately none worked.

  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\baza.mdf;Initial Catalog=baza;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
  </connectionStrings>

and the Main

  static void Main(string[] args) {

        Console.WriteLine("BEFORE:" + AppDomain.CurrentDomain.GetData("DataDirectory"));
        string relative = @"..\..\App_Data\Cos.mdf";
        string absolute = Path.GetFullPath(relative);
        absolute = Path.GetDirectoryName(@absolute);
        AppDomain.CurrentDomain.SetData("DataDirectory", @absolute);
        Console.WriteLine(@absolute);
        Console.WriteLine(AppDomain.CurrentDomain.GetData("DataDirectory"));
        Console.ReadKey();
}

then I get in console:

enter image description here

and after deleting Migrations directory and enable-migrations, automatic migrations to true, update-database I get:

PM> update-database Specify the '-Verbose' flag to view the SQL statements being applied to the target database. System.Data.SqlClient.SqlException (0x80131904): A file activation error occurred. The physical file name '\baza.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<NonQuery>b__0(DbCommand t, DbCommandInterceptionContext1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.NonQuery(DbCommand command, DbCommandInterceptionContext interceptionContext) at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass1a.b__19(DbConnection conn) at System.Data.Entity.SqlServer.SqlProviderServices.<>c__DisplayClass33.b__32() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<>c__DisplayClass1.b__0() at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func1 operation) at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Action operation) at System.Data.Entity.SqlServer.SqlProviderServices.UsingConnection(DbConnection sqlConnection, Action1 act) at System.Data.Entity.SqlServer.SqlProviderServices.UsingMasterConnection(DbConnection sqlConnection, Action1 act) at System.Data.Entity.SqlServer.SqlProviderServices.CreateDatabaseFromScript(Nullable1 commandTimeout, DbConnection sqlConnection, String createDatabaseScript) at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase() at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection) at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.EnsureDatabaseExists(Action mustSucceedToKeepDatabase) at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration) at System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update(String targetMigration) at System.Data.Entity.Migrations.Design.ToolingFacade.UpdateRunner.Run() at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate) at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner) at System.Data.Entity.Migrations.Design.ToolingFacade.Update(String targetMigration, Boolean force) at System.Data.Entity.Migrations.UpdateDatabaseCommand.<>c__DisplayClass2.<.ctor>b__0() at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command) ClientConnectionId:23ca49c1-4797-4bc3-8f16-f34fd77f2cbe A file activation error occurred. The physical file name '\baza.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors. PM>

评论

Problem 1 (of 2)

When you set the value of DataDirectory, it needs to be a directory, not a file. You are passing in the value of the absolute variable which is:

C:\Users\s8359_000\Documents\Visual Studio 2013\Projects\Projekt5 — kopia\Projekt5\App_Data\Cos.mdf

and which contains the filename. That is not valid. DataDirectory is a substitution value, so specifying:

AttachDbFilename=|DataDirectory|\Cos.mdf

in the connection string would translate into:

C:\Users\s8359_000\Documents\Visual Studio 2013\Projects\Projekt5 — kopia\Projekt5\App_Data\Cos.mdf\Cos.mdf

That is not a valid path. So it appears that .NET sees that the value of DataDirectory is not valid and does not use it and hence starts in the current working directory.

Use Path.GetDirectoryName(relative) instead of Path.GetFullPath(relative) to set the value of absolute and it should work as it will set the value of DataDirectory to be:

C:\Users\s8359_000\Documents\Visual Studio 2013\Projects\Projekt5 — kopia\Projekt5\App_Data

The MSDN page for Connection Strings has some additional details towards the bottom, in the section titled, "Support for the |DataDirectory| Substitution String..."

Problem 2 (of 2)

  1. "DataDirectory" is set in the AppDomain.
  2. Console Apps have their own AppDomains that are created when they start and go away when they exit.
  3. Package Manager (where you are running Update-Database) does not have access to the AppDomain of your console app where you are setting the value of "DataDirectory".
  4. You need to either:
    1. programatically set "DataDirectory" in Package Manager, or
    2. programatically run "update-database" within the context of your console app

I don't know how to programatically interact with Package Manager, but I did manage to figure out how to programatically fire the "update-database" process. Just add the following line just after you set the value of "DataDirectory":

Database.SetInitializer(new
    MigrateDatabaseToLatestVersion<YourDataContextName, Configuration>()
 );

You will also need at least one, if not two, using statements:

  • using System.Data.Entity;
  • using ProjectName.Migrations; // namespace of Migrations\Configuration.cs

Please note that this alone does not create the database. Any pending changes will be published when you first access the database via the DbContext.

Example:

using System.Data.Entity;
using Projekt5.Migrations;

....

string relative = @"..\..\App_Data\Cos.mdf";
string absolute = Path.GetDirectoryName(absolute);
AppDomain.CurrentDomain.SetData("DataDirectory", absolute);
Database.SetInitializer(new
    MigrateDatabaseToLatestVersion<Projekt5Context, Configuration>()
 );
// database not created yet

using (var db = new Projekt5Context())
{
  db.Things.Add(new Thing { Name = "OMG This works!" });
  db.SaveChanges();
} 
// database CREATED!

Also, you might need to call the following, one time, via Package Manager (it doesn't do anything immediately to the database so the connection string is not accessed):

Add-Migration InitialMigration

For more info, please see the MSDN page for Code First Migrations.

Once this line of code to call SetInitializer is there with MigrateDatabaseToLatestVersion, it does just that: each time it runs (which is why this is done at the beginning of the console app) it syncs any changes between what is in the "model" (that is now compiled into the Assembly) and the database, making sure that the database has the latest version. This assumes that any new tables are represented in the DbContext class. But no additional Package Manager commands need to be ran.

You can set DataDirectory for Update-Database in Configuration class which was created by Enable-Migrations command:

internal sealed class Configuration : DbMigrationsConfiguration<DataContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        var dataDirPath = "<YourPath>";
        AppDomain.CurrentDomain.SetData("DataDirectory", dataDirPath);
    }
}

To point the DataDirectory to a folder named 'AppData' under the console project and EF code first migrations you must do the following:

public static class AppData
{
    public static void Set()
    {
        // Set the |DataDirectory| path used in connection strings to point to the correct directory for console app and migrations
        var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
        string relative = @"..\..\App_Data\";
        string absolute = Path.GetFullPath(Path.Combine(baseDirectory, relative));
        AppDomain.CurrentDomain.SetData("DataDirectory", absolute);
    }
}

Then call AppData.Set() from the entry point of the console application and database migrations:

1) Console application's Main-method or Startup-class:

class Program
{
    static void Main()
    {
         AppData.Set();
    }
}

2) EF code first migrations

public class DatabaseContext : DbContext
{
    // Add this constructor to your database context
    public DatabaseContext() : base()
    {
        AppData.Set();
    }

    // DbSet's are defined here
}

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐
  • 尝试为文件…database1.mdf附加自动命名的数据库失败(An attempt to attach an auto-named database for file …database1.mdf failed)
    问题 调试Visual Studio 2010网站时出现以下错误: 尝试为文件C:\ Users ... \ Desktop \ Dpp2012New \ App_Data \ dppdatabase.mdf附加自动命名的数据库失败。 存在具有相同名称的数据库,或者无法打开指定的文件,或者该数据库位于UNC共享上。 说明:执行当前Web请求期间发生未处理的异常。 请查看堆栈跟踪,以获取有关错误及其在代码中起源的更多信息。 异常详细信息:System.Data.SqlClient.SqlException:尝试为文件C:\ Users ... \ Desktop \ Dpp2012New \ App_Data \ dppdatabase.mdf附加自动命名数据库的尝试失败。 存在具有相同名称的数据库,或者无法打开指定的文件,或者该数据库位于UNC共享上。 这是我的web.config连接字符串: <connectionStrings> <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
  • WebConfig.ConnectionString中的相对路径参考(Relative path reference in WebConfig.ConnectionString)
    问题 是否可以在web.config中的connectionstring,attachDbFileName属性中指定相对路径引用? 例如,在我的数据库位于App_data文件夹中,我可以轻松地将AttachDBFilename指定为| DataDirectory | \ mydb.mdf和| Datadirectory |。 将自动解析为正确的路径。 现在,假设web.config文件位于A文件夹中,但是数据库位于B \ App_data文件夹中,其中A和B文件夹位于同一文件夹中。 无论如何,有没有使用相对路径引用来解析为正确路径的方法? 回答1 在以下情况下,我遇到了同样的问题:我想使用与集成测试中的应用程序相同的数据库。 我采用以下解决方法: 在我的测试项目的App.config中,我有: <appSettings> <add key="DataDirectory" value="..\..\..\BookShop\App_Data\"/> </appSettings> 在测试设置中,我执行以下代码: var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"]; var absoluteDataDirectory = Path.GetFullPath(dataDirectory)
  • 实体框架代码优先的SQL Server Express连接字符串(SQL Server Express connection string for Entity Framework Code First)
    问题 我正在Visual Web Developer 2010 Express中工作,并使用Entity Framework代码优先CTP。 我可以使用新的SQL Server CE来执行此操作,但是找不到与SQL Server Express一起使用的连接字符串。 使用SQL Server CE beta版的该版本可以正常工作(在更改模型后创建并重新创建数据库)。 <add name="TrempimModel" connectionString="data source=|DataDirectory|TrempimModel.sdf" providerName="System.Data.SqlServerCe.4.0" /> 这是我从aspnetdb连接字符串中复制的, <add name="TrempimModel" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI; AttachDBFilename=|DataDirectory|TrempimModel.mdf;User Instance=true" providerName="System.Data.SqlClient" /> 在启动时给出以下消息: 无法完成操作。 提供的SqlConnection没有指定初始目录 那么如何使其与SQL
  • 我如何读取| DataDirectory |的当前路径。 从配置设置(How do I read the current path of |DataDirectory| from config settings)
    问题 我正在编写一个程序,要求用户在应用程序启动时选择活动数据库。 我有一个Windows窗体,该窗体将列出存储在ApplicationData子文件夹中的数据库,该子文件夹专门用于存储数据库文件。 但是,当我创建一个新数据库时,我需要复制模板数据库,但是无法确定默认情况下该数据库的存储位置。 我试过了: dpath = ConfigurationManager.AppSettings["DataDirectory"]; 我似乎总是得到一个空值作为回报。 有一次我放弃了,以为我可以将DataDirectory设置为我选择的文件夹,但是看来我在执行程序时太晚了,无法使其生效。 newdpath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\MyAppFolder"; 对于如何找到数据库的位置,或者我自己尽早设置数据库以影响程序操作的任何建议,我将不胜感激。 编辑: 对于第二部分,我发现我已经在执行TableAdapter.Fill命令之后试图修改连接字符串,从而解释了为什么要打开默认数据库。 这个谜已经解决了。 但是,第一部分仍然是一个未知数。 谢谢你。 回答1 |DataDirectory| 不是来自配置设置; 您混淆了三种不同的东西: ConfigurationManager
  • 如何使用C#连接到MS Access文件(mdb)?(How to connect to a MS Access file (mdb) using C#?)
    问题 我正在尝试连接到mdb文件,并且我知道我需要Microsoft.OLEDB.JET.4.0数据提供程序。 不幸的是,我没有在(大学)机器上安装它。 由于他们不提供该提供程序,因此我认为应该有一个解决方法。 在没有Microsoft.OLEDB.JET.4.0的情况下,如何连接文件?或者有其他选择吗? 我有以下提供商: 我曾尝试使用OLE DB Provider for Microsoft Directory Services ,在测试连接时,我得到“测试成功,但提供程序未接受某些设置”。 我采用了该字符串并使用了它,但ADsDSOObject' failed with no error message available, result code: DB_E_ERRORSINCOMMAND(0x80040E14) 。 回答1 最简单的连接方式是使用如下代码通过OdbcConnection进行连接 using System.Data.Odbc; using(OdbcConnection myConnection = new OdbcConnection()) { myConnection.ConnectionString = myConnectionString; myConnection.Open(); //execute queries, etc }
  • 配置多个数据库实体框架6(Configure multiple database Entity Framework 6)
    问题 在我的解决方案中,我有2个使用Entity Framework 6的项目。每个项目都指向不同的数据库,两个数据库都使用相同的数据提供-SQL Server。 我的解决方案中的第三个项目需要同时使用两个数据库。 我的问题是如何配置这些上下文。 我试图在单独的程序集中创建配置类: namespace OSAD_Base { class EfDbConfiguration : DbConfiguration { public EfDbConfiguration() { SetProviderServices(SqlProviderServices.ProviderInvariantName, SqlProviderServices.Instance); } } } 并在每个上下文类中引用此配置: namespace IntegrationDb { [DbConfigurationType("OSAD_Base.EfDbConfiguration, OSAD_Base")] public partial class IntegrationEntities : DbContext { public IntegrationEntities(string connectionString) : base(connectionString) { } } } 当初始化我的第一个时,一切正常
  • 应用程序无法搭建物品(Application can't scaffold items)
    问题 我在VS 2013 Professional中创建了MVC 5应用程序,然后首先将EF 6.1代码与SQL Server Express上的现有数据库一起使用。 当我尝试创建视图时,我使用的是“新支架项目…”,然后选择“使用Entity Framework的带有视图的MVC 5控制器”。 我选择模型和上下文类,然后单击“确定”。 然后出现以下错误信息,并且没有代码被创建。 我已经卸载了EF Power Tools并出现了同样的错误。 错误 运行所选代码生成器时发生错误:“调用目标已引发异常。” 我还尝试了卸载/重新安装VS 2013和SQL Server且未做任何更改。 关于什么可能导致此错误的任何其他想法? 回答1 我也遇到了这个问题,我通过在数据库上下文中调用base.onModelCreating解决了该问题。 base.OnModelCreating(modelBuilder); 回答2 就我而言,我将连接字符串从Web.config中移到了 <connectionStrings configSource="ConnectionStrings.config"/> 当我尝试搭建脚手架时开始出现错误时。 运行所选代码生成器时发生错误:“调用目标已引发异常。” 将我的连接字符串移回Web.config解决了我的问题。 回答3 这为我解决了这个问题,
  • 无法将文件* .mdf作为数据库附加(Cannot attach the file *.mdf as database)
    问题 基本上,我已按照教程进行操作,并决定稍后删除.mdf文件。 现在,每当我尝试运行该应用程序时,都会出现以下错误(该线程的标题)。 出现错误的代码如下所示(ASP.NET MVC 4): OdeToFoodDB db = new OdeToFoodDB(); public ActionResult Index() { var model = db.Restaurants.ToList(); return View(model); } 我的连接字符串如下: <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=OdeToFoodDb;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\OdeToFoodDb.mdf" providerName="System.Data.SqlClient" /> 我尝试查看SQL Server对象资源管理器,但看起来如下所示: 另外,在服务器资源管理器中,我看不到任何数据连接。 当我尝试在Server Explorer中添加新连接时,我看不到任何名为OdeToFoodDb数据库。 抱歉,这个问题很广泛,但是我是Entity Framework的新手
  • 在MVC4中添加控制器不起作用(Add Controller in MVC4 not working)
    问题 我正在使用VS 2010 Premium。 我有一个使用SqlCe 4.0和实体框架模型的MVC4项目。 型号是: public class ProjectBuild { public int ProjectBuildID {get;set;} public string name {get;set;} } public class ProjectBuildContext:DbContext { public DbSet<ProjectBuild> builds {get;set;} } 以下是我的连接字符串: add name="ProjectBuildContext" connectionString="Data Source=|DataDirectory|DB.sdf" providerName="System.Data.SqlServerCe.4.0" 当我也尝试使用内置脚手架创建新控制器时,出现以下错误: “无法为ProjectBuild检索元数据。”不支持使用相同的DbCompiledModel来针对不同类型的数据库服务器创建上下文,而是为所使用的每种服务器类型创建一个单独的DbCompiledModel。 回答1 我尝试了Fontanka16解决方案,但没有成功,事实证明我的DbContext类缺少定义目标CE数据库的默认构造函数。 这些是我的步骤摘要:
  • Reading connection string from external config file
    I have created a console application and an app.config file and Connections.config file. The app.config file has a connectionstring property source pointing to the Connections.config When I tried to read the connection string in the application, I get a ConfigurationErrorException This is my main method. static void Main(string[] args) { var settings = ConfigurationManager.ConnectionStrings; if (settings != null) { foreach (ConnectionStringSettings setting in settings) { Console.WriteLine(setting.ConnectionString); } } } App.config file <?xml version="1.0" encoding="utf-8" ?> <configuration>
  • EF5:无法将文件“ {0}”作为数据库“ {1}”附加(EF5: Cannot attach the file ‘{0}' as database '{1}')
    问题 我遇到了此处所述的确切问题(请参阅“无法附加到已删除的MDF文件”部分),但此处未告知问题的解决方案... 简而言之,问题在于,删除.mdf文件后,当我尝试使用EF 5.0访问数据库时会引发以下异常。 DataException-> EntityException-> SqlException: 无法将文件“ {0}”作为数据库“ {1}”附加 我确实删除了数据库文件,现在在运行应用程序时期望它使用其初始化程序时收到该讨厌的错误消息。 有任何解决这个问题的方法吗? 回答1 如果删除该数据库文件,它仍然保持在SqlLocalDB的注册状态。 有时它会修复它以删除数据库。 您可以从命令行执行此操作。 打开“开始/程序”菜单下的“ Visual Studio开发人员命令提示符”。 运行以下命令: sqllocaldb.exe stop v11.0 sqllocaldb.exe delete v11.0 回答2 对于那些仍在寻找解决方案的人... 转到“查看/ SQL Server对象资源管理器”,然后从(localdb)\ v11.0子节点中删除数据库! 本质上是保留了应保存文件位置的本地数据库,如果要删除数据库文件,请确保将其从此资源管理器实用程序中删除,而不是手动删除。 回答3 我确实首先尝试了JSobell的解决方案,但是没有看到我的数据库在那列出。 我从VS
  • SQL Express连接字符串:相对于应用程序位置的mdf文件位置(SQL Express connection string: mdf file location relative to application location)
    问题 我将SQL Express数据库用作c#中的单元测试项目的一部分。 我的数据库位于这里: ./Databases/MyUnitTestDB.mdf 我想在app.config使用相对路径或变量,而不是将我的连接字符串定义为: AttachDbFilename=C:\blah\blah\blah\yea\yea\yea\MyApplication\Databases\MyUnitTestDB.mdf 我已经看过|DataDirectory|的用法但是我认为这仅适用于Web应用程序正确吗? 我想在应用程序配置文件中对此进行控制,因为在生产中,应用程序使用托管的sql数据库。 回答1 谢谢大家,我结合了您的回答。 在我的app.config文件中,我的连接字符串定义如下 <add name="MyConnectionString" connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" /> 在我的单元测试类中,我使用以下命令设置DataDirectory属性 [TestInitialize] public void TestInitialize() {
  • What does “The ”DataDirectory“ registry value is missing in the LocalDB instance registry key” error mean?
    I have a MVC4/ASP.Net application that uses localdb. Everything "appears" to work correctly. However I am getting loads of errors in my event log: The "DataDirectory" registry value is missing in the LocalDB instance registry key: {BB3F4304-E7E9-4EE7-9A25-B46BFAA73FB4} The "DataDirectory" registry value is missing in the LocalDB instance registry key: {BB31321B-BEB9-465B-8C8E-DEF9C2C67FBE} Each time the instance changes. XML Detail of the error: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="SQLLocalDB 11.0" /> <EventID Qualifiers="35269">512<
  • EF 5 + SQL Server CE 4:如何为数据库文件指定自定义位置?(EF 5 + SQL Server CE 4: How to specify custom location for database file?)
    问题 我正在开发需要小型本地数据库的客户端系统。 我想避免安装SQL Server Express,并决定使用SQL Server 4。 我使用Entity Framework 5进行数据访问,并创建了自定义上下文。 在开发中一切正常,在这里我可以使用app.config设置特定文件位置或动态Data Source=|DataDirectory|\MyDatabase.sdf 。 但是在部署时,我希望数据库位于用户文档文件夹中: \My Documents\ApplicationName\MyDatabase.sdf 我怎样才能做到这一点? 我所需要做的实际上就是能够在代码中设置自定义连接字符串! 这是我到目前为止尝试过的: private MyApplicationDataContext(string connectionString) : base(connectionString) { } public static MyApplicationDataContext CreateInstance() { var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var path = Path.Combine(directory, @"ApplicationName
  • Why saving changes to a database fails?
    I have following C# code in a console application. Whenever I debug the application and run the query1 (which inserts a new value into the database) and then run query2 (which displays all the entries in the database), I can see the new entry I inserted clearly. However, when I close the application and check the table in the database (in Visual Studio), it is gone. I have no idea why it is not saving. using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlServerCe; using System.Data
  • Delete parent with children in one to many relationship
    I have a .NET4.0 application with Entity Framework 5.0 e Sql Server CE 4.0. I have two entities with a one to many (parent/child) relationship. I've configured it to cascade delete on parent removal, but for some reason it doesn't seem to work. Here is a simplified version of my entities: public class Account { public int AccountKey { get; set; } public string Name { get; set; } public ICollection<User> Users { get; set; } } internal class AccountMap : EntityTypeConfiguration<Account> { public AccountMap() { this.HasKey(e => e.AccountKey); this.Property(e => e.AccountKey)
  • 如何使用SQL Server CE和C#更新dB表中的单元格值(Visual Studio 2010)(How can I update a cell value in a dB table, using SQL Server CE and C# (Visual Studio 2010))
    问题 我正在为大学编写一个小型应用程序,一个视频出租应用程序。 从数据库中读取数据没有问题,但是无法更新表中的数据。 特别是,我希望更新显示某人租借电影后的库存电影数量的单元格。 到目前为止,我一直在尝试这样做: string updateDVDs = "UPDATE Products SET dvd_quantity = " + product.Quantity + " WHERE title = '"+ product.Name +"';"; cmdUpdateDVDs = new SqlCeCommand(updateDVDs, dBConnection); dBConnection.Open(); cmdUpdateDVDs.ExecuteNonQuery(); dBConnection.Close(); 我没有收到任何错误,但是表格中的单元格没有更新。 任何帮助将不胜感激,如果您需要更多信息,请告诉我。 更新:好的,我有一些有趣的进展,我已经将代码更新为: string updateDVDs = "UPDATE Products SET dvd_quantity = " + product.Quantity + " WHERE title = '" + product.Name + "'"; dBConnection = new SqlCeConnection
  • 如何设置SQL Server连接字符串?(How can I set an SQL Server connection string?)
    问题 我正在开发一个简单的C#应用​​程序,我想知道这一点:当我将应用程序连接到PC上的SQL Server时,我知道连接字符串(服务器名称,密码等),但是当我连接它时到另一台PC,SQL Server连接字符串是不同的。 SQL Server中是否有一个可以连接的默认帐户附带的普通帐户? 我听说过SQL Server中的sa帐户。 什么是sa ? 回答1 .NET DataProvider-使用用户名和密码的标准连接 using System.Data.SqlClient; SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Data Source=ServerName;" + "Initial Catalog=DataBaseName;" + "User id=UserName;" + "Password=Secret;"; conn.Open(); .NET DataProvider-可信连接 SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Data Source=ServerName;" + "Initial Catalog=DataBaseName;" + "Integrated Security=SSPI
  • Datagridview将更改保存到数据库vb.net(Datagridview save changes to Database vb.net)
    问题 您好,我有一个databse,我已将其加载到vb.net应用程序中的Datagridview。 它加载很好,但是当我尝试保存日期时,它不起作用。 这是代码 Private myConString As String Private con As OleDbConnection = New OleDbConnection Private Dadapter As OleDbDataAdapter Private DSet As DataSet Private DSet2 As DataSet Private ConCMD As OleDb.OleDbCommand Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load myConString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=e:\Database31.accdb" con.ConnectionString = myConString con.Open() Dadapter = New OleDbDataAdapter("select * from Table1", con) DSet = New DataSet Dadapter.Fill
  • Web.Config Debug/Release
    I know that web.config in Visual Studio 2010 provides the ability to switch from databases from Debug mode to Release mode. Here is my Web.Release.config: <?xml version="1.0"?> <!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 --> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <connectionStrings> <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />