17
votes
    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; }
}

I am trying to create a new database using Entity Framework but I always getting that exception

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: }

Line 30 throws the exception

I hope somebody can help

2
Does the c:\users\oren\documents\visual studio 2012\Projects\ResturantSite\ResturantSite\App_Data folder exist? And if so, does the application have permission to write to it? - DavidG
the folder doesent exist how do i know if the app have permission to write it? - Erez
Create it and see what happens! - DavidG
Visual Studio has the option to do that specific folder automatically. - DavidG
i am trying to create that database by entity - Erez

2 Answers

54
votes

Your application is missing the App_Data folder. Right click on your project, select Add, then Add ASP.Net Folder and choose the App_Data folder.

This ensures the correct folder exists for your application.

3
votes

I fixed the error deleting the current Add_Data folder since I had cloned the project from a Github repository, then I added the App_Data folder again and ran the migrations with update-database command. This worked for me.