3

我是 asp.net core 的新手,我想做的任务应该很简单。使用 Visual Studio,我正在尝试将 .mdf 文件作为本地数据库链接到我的项目。由于我想让它适用于多台计算机,我需要从 appsettings.json 中找到数据目录文件夹路径。因此,经过一些研究,最好的方法是使用|DataDirectory| 替换字符串。

问题是我的网站无法通过这种方式访问​​我的 mdf 文件,它会生成 ArgumentException : "Invalid value for key 'attachdbfilename'"。虽然我找到了一些关于这个问题的话题,但这些话题都没有回答我的问题。

我已经尝试使用完整路径来查找我的文件并且它有效,但正如我所说,我需要从几台计算机中找到它。

这里是 Startup.cs 和 appsettings.json

启动.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            string path = Path.Combine(Directory.GetCurrentDirectory(), "App_Data");
            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>()
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
        [...]
   }

我的连接字符串,在appsettings.json

"ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDbFilename=|DataDirectory|\\aspnet-MatrixCalculatorApp-db.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

如果需要,我还可以提供堆栈跟踪。

预先感谢您的帮助。

4

1 回答 1

3

Well, if someone still has the same issue as I had, I just found a solution :

You can simply replace the occurence of a string, with the path of your data folder.

Startup.cs :

string path = Path.Combine(Directory.GetCurrentDirectory(), "App_Data");

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection").Replace("[DataDirectory]", path)));
            services.AddDefaultIdentity<IdentityUser>()

appsettings.json

"DefaultConnection": "Server=(localdb)\\mssqllocaldb;AttachDbFilename=[DataDirectory]\\aspnet-MatrixCalculatorApp-db.mdf;Trusted_Connection=True;MultipleActiveResultSets=true"

I replaced |DataDirectory| with [DataDirectory] to avoid program confusion with the substitution string. But if someone has a better explanation than me, it would be nice to do it.

于 2019-05-02T22:15:38.903 回答