c# - .mdf"failed with the operating system error 2(系统找不到指定的文件。)

标签 c# sql asp.net database entity-framework

    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 文件夹。右键单击您的项目,选择 Add,然后选择 Add ASP.Net Folder 并选择 App_Data 文件夹。

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

关于c# - .mdf"failed with the operating system error 2(系统找不到指定的文件。),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24145607/

相关文章:

c# - 有时是数组有时是对象时反序列化JSON

c# - 从 Angular 2 到 ASP.net Core 的 POST 请求不起作用。服务器端的空值

python - 为什么这个Python错误代码是: Too Few parameters. Expected1。 (-3010) 使用 pyodbc 时发生?

sql - 使用一个标签查找域?

c# - 如何从 SQL 中检索多个值到标签

c# - LINQ 沿着对象树查询需要匹配的值

MySQL 查询极慢有什么建议吗?

.net - 数据服务抛出神秘异常 : "Media type requires a ' /' character"

c# - ASP.NET MVC 4 自定义 404 页面

c# - 有没有办法在不使用 await foreach 的情况下返回 IAsyncEnumerable