C# · 12月 26, 2021

c# – .mdf“出现操作系统错误2(系统找不到指定的文件)

protected void register_Click(object sender,EventArgs e) { AddUser(userName.Text,password.Text,confirm.Text); } void AddUser(string name,string pass,string confirm) { User u = new User(name,pass,confirm); if (u.Valid) { using (var db = new SiteContext()) { db.User.Add(u); db.SaveChanges(); } } }}public class User { public int UserId { get; set; } public string UserName { get; set; } public string Password { get; set; } public bool Valid { get; set; } public User(string _name,string _password,string _confirm) { if (CheckPassword(_password,_confirm)) { Password = _password; UserName = _name; Valid = true; } else Valid = false; } private bool CheckPassword(string _password,string _confirm) { if (_confirm.Equals(_confirm)) return true; return false; }}public class SiteContext : DbContext { public DbSet<User> User { get; set; }}

我试图使用Entity Framework创建一个新的数据库,但是我总是得到这个异常

Directory lookup for the file “c:\users\oren\documents\visual studio 2012\Projects\ResturantSite\ResturantSite\App_Data\ResturantSite.SiteContext.mdf” Failed with the operating system error 2(The system cannot find the file specified.).
CREATE DATABASE Failed. Some file names listed Could not be created. Check related errors

Line 28: using (var db = new SiteContext())
Line 29: {
Line 30: db.User.Add(u);
Line 31: db.SaveChanges();
Line 32: }

第30行抛出异常

我希望有人能帮忙

解决方法 您的应用程序缺少App_Data文件夹.右键单击您的项目,选择添加,然后添加ASP.Net文件夹,然后选择App_Data文件夹.

这确保您的应用程序存在正确的文件夹.