0

While checking whether the user exists in the database, this happens "The entity type User is not part of the model for the current context".

"Sorry for my bad english"

This my Context:

public class UserContext : DbContext
{

    public UserContext() :
    base("PracticeDB")
    {

    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<PracticeDB>().ToTable("Users");
    }
    public DbSet<User> Users { get; set; }
}

View model:

    namespace Models.Models
{
    public class LoginModel
    {
        [Required]
        public string Name { get; set; }
        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }
    }
}

Controller:

namespace Models.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model)
        {
            if (ModelState.IsValid)
            {
                User user = null;
                using (UserContext db = new UserContext())
                {
                    user = db.Users.FirstOrDefault(u => u.Name == model.Name && u.Password == model.Password);

                }
                if (user != null)
                {
                    FormsAuthentication.SetAuthCookie(model.Name, true);
                    return RedirectToAction("Users");
                }
                else
                {
                    ModelState.AddModelError("", "Пользователя с таким логином и паролем нет");
                }
            }

            return View(model);
        }

    }
}

enter image description here

JonnyJon44
  • 73
  • 1
  • 11
  • Have a look at this question: http://stackoverflow.com/questions/20688922/the-entity-type-type-is-not-part-of-the-model-for-the-current-context The cause here was a wrong connection string in web.config. – Dabblernl Jan 18 '16 at 23:24

2 Answers2

0

I think this line in your UserContext:

modelBuilder.Entity<PracticeDB>().ToTable("Users");

Needs to change to:

modelBuilder.Entity<User>().ToTable("Users");
Jason
  • 1,065
  • 1
  • 16
  • 26
0

You need to tell the DbContext about the User model in OnModelCreating. Try changing the PracticeDB model to User in modelBuilder.Entity<PracticeDB>().ToTable("Users");.

Donald
  • 1,120
  • 12
  • 21