c# #asp.net-mvc #web-applications #ado.net #crud
#c# #asp.net-mvc #веб-приложения #ado.net #crud
Вопрос:
Я продолжаю получать это исключение, когда пытаюсь зарегистрировать пользователя в своей базе данных. Я попробовал несколько решений, но проблема все еще сохраняется. Включая эти: https://entityframework.net/knowledge-base/20688922/the-entity-type—type—is-not-part-of-the-model-for-the-current-context
Я получаю исключение при отправке формы, и исключение возникает, когда эта функция пытается выполнить:
У меня есть два контекста БД:
namespace CRUDProject.Models
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class DeskDatabaseUsers : DbContext
{
public DeskDatabaseUsers(): base("name=DeskDatabaseUsers")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("User");
}
public virtual DbSet<User> User { get; set; }
}
}
namespace CRUDProject.Models
{
using System;
using System.Data.Entity;
using CRUDProject.Extensions;
using System.Data.Entity.Infrastructure;
public partial class DeskDatabaseEntities : DbContext
{
public DeskDatabaseEntities():base("name=DeskDatabaseEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Table>().ToTable("Table");
}
public virtual DbSet<Table> Table { get; set; }
}
}
мой код ниже:
Контроллер:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CRUDProject.Extensions;
using System.Data.Entity;
using System.Web.Mvc;
using CRUDProject.Models;
using System.Net.Mail;
using System.Net;
using System.Data.Entity.Validation;
using System.Web.Util;
namespace CRUDProject.Models
{
public class TableController : Controller
{
public ActionResult Index()
{
using (DeskDatabaseEntities dbModel = new DeskDatabaseEntities())
{
return View(dbModel.Table.ToList());
}
}
[HttpGet]
//GET: Table/Registration
public ActionResult Registration()
{
return View();
}
//GET: Table/Login
public ActionResult Login()
{
return View();
}
// GET: Table/Details/5
public ActionResult Details(int id)
{
using (DeskDatabaseEntities dbModel = new DeskDatabaseEntities())
{
return View(dbModel.Table.Where(x=>x.Id==id).FirstOrDefault());
}
}
// GET: Table/Create
public ActionResult Create()
{
return View();
}
// POST: Table/Create
[HttpPost]
public ActionResult Create(Table table)
{
try
{
using (DeskDatabaseEntities dbModel = new DeskDatabaseEntities())
{
dbModel.Table.Add(table);
dbModel.SaveChanges();
this.AddNotification("Sikeres asztalfoglalás!", NotificationType.SUCCESS);
}
}
catch (Exception)
{
this.AddNotification("Sikertelen asztalfoglalás!", NotificationType.ERROR);
}
return View();
}
// GET: Table/Edit/5
public ActionResult Edit(int id)
{
using (DeskDatabaseEntities dbModel = new DeskDatabaseEntities())
{
return View(dbModel.Table.Where(x => x.Id == id).FirstOrDefault());
}
}
// POST: Table/Edit/5
[HttpPost]
public ActionResult Edit(int id, Table table)
{
try
{
using (DeskDatabaseEntities dbModel = new DeskDatabaseEntities())
{
dbModel.Entry(table).State = EntityState.Modified;
dbModel.SaveChanges();
this.AddNotification("Sikeres változtatás", NotificationType.SUCCESS);
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Table/Delete/5
public ActionResult Delete(int id)
{
using (DeskDatabaseEntities dbModel = new DeskDatabaseEntities())
{
return View(dbModel.Table.Where(x => x.Id == id).FirstOrDefault());
}
}
#region NonActionSegment
[NonAction]
public void SendVerificationLinkEmail(string emailID, string activationCode)
{
var verifyUrl = "/User/VerifyAccount/" activationCode;
var link = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery, verifyUrl);
var fromEmail = new MailAddress("finywow@gmail.com", "Dotnet Awesome");
var toEmail = new MailAddress(emailID);
var fromEmailPassword = "********"; // Replace with actual password
string subject = "Your account is successfully created!";
string body = "<br/><br/>We are excited to tell you that your Dotnet Awesome account is"
" successfully created. Please click on the below link to verify your account"
" <br/><br/><a href='" link "'>" link "</a> ";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromEmail.Address, fromEmailPassword)
};
using (var message = new MailMessage(fromEmail, toEmail)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
smtp.Send(message);
}
[NonAction]
public bool IsEmailExist(string emailID)
{
using (DeskDatabaseUsers dc = new DeskDatabaseUsers())
{
var v = dc.User.Where(a => a.EmailID == emailID).FirstOrDefault();
return v != null;
}
}
#endregion
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Registration([Bind(Exclude = "IsEmailVerified,ActivationCode")] User user)
{
bool Status = false;
string message = "";
//
// Model Validation
if (ModelState.IsValid)
{
#region //Email is already Exist
var isExist = IsEmailExist(user.EmailID);
if (isExist)
{
ModelState.AddModelError("EmailExist", "Email already exist");
return View(user);
}
#endregion
#region Generate Activation Code
user.ActivationCode = Guid.NewGuid();
#endregion
#region Password Hashing
user.Password = Crypto.Hash(user.Password);
user.ConfirmPassword = Crypto.Hash(user.ConfirmPassword); //
#endregion
user.IsEmailVerified = false;
#region Save to Database
using (DeskDatabaseUsers dc = new DeskDatabaseUsers())
{
dc.User.Add(user);
dc.SaveChanges();
//Send Email to User
SendVerificationLinkEmail(user.EmailID, user.ActivationCode.ToString());
message = "Registration successfully done. Account activation link "
" has been sent to your email id:" user.EmailID;
Status = true;
}
#endregion
}
else
{
message = "Invalid Request";
}
ViewBag.Message = message;
ViewBag.Status = Status;
return View(user);
}
[HttpGet]
public ActionResult VerifyAccount(string id)
{
bool Status = false;
using (DeskDatabaseUsers dbmod=new DeskDatabaseUsers())
{
dbmod.Configuration.ValidateOnSaveEnabled = false;
var v = dbmod.User.Where(a => a.ActivationCode == new Guid(id)).FirstOrDefault();
if (v!=null)
{
v.IsEmailVerified = true;
dbmod.SaveChanges();
Status = true;
}
else
{
ViewBag.Message = "Invalid Request";
}
}
ViewBag.Status = Status;
return View();
}
// POST: Table/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)// NOT SURE IF THIS WORKS PROPERLY
{
try
{
using (DeskDatabaseEntities dbModel = new DeskDatabaseEntities())
{
Table table = dbModel.Table.Where(x => x.Id == id).FirstOrDefault();
this.AddNotification("Sikeres törlés", NotificationType.SUCCESS);
dbModel.Table.Remove(table);
dbModel.SaveChanges();
}
}
catch (Exception)
{
this.AddNotification("Az elem már törlésre került", NotificationType.ERROR);
}
return View();
}
}
}
Комментарии:
1. Функция, в которой появляется исключение: ` [NonAction] public bool IsEmailExist(string emailID) { using (DeskDatabaseUsers dc = new DeskDatabaseUsers()) { var v = dc.User . Где(a => a.EmailID == emailID).FirstOrDefault(); возвращает v != null; } }`
2. Добавьте DbSet<User> в контекст DeskDatabaseEntities
3. К сожалению, исключение все еще появляется