问题描述
我正在尝试使用Entity Framework创建注册屏幕,并且我不使用数据库。使用我的模型的上下文
我正在遵循有关如何执行该操作的指南,但是使用数据库,并且在从控制器创建视图时出现此错误:
登录控制器:
public class loginController : Controller
{
private loginContext db = new loginContext();
// GET: login
public ActionResult Index()
{
return View();
}
[AllowAnonymous]
[HttpPost]
public ActionResult Index(login lc)
{
string mainconn = ConfigurationManager.ConnectionStrings["loginContext"].ConnectionString;
sqlConnection sqlconn = new sqlConnection(mainconn);
string sqlquery = "select email,password from logins where email=@email and password=@password";
sqlconn.open();
sqlCommand sqlcomm = new sqlCommand(sqlquery,sqlconn);
sqlcomm.Parameters.AddWithValue("@email",lc.email);
sqlcomm.Parameters.AddWithValue("@password",lc.password);
sqlDataReader sdr = sqlcomm.ExecuteReader();
if (sdr.Read())
{
FormsAuthentication.SetAuthCookie(lc.email,true);
Session["emailid"] = lc.email.ToString();
return RedirectToAction("Welcome","Login");
}
else
{
ViewData["mensage"] = "Username & Password are wrong:";
}
sqlconn.Close();
return View();
}
public ActionResult welcome()
{
return View();
}
}
模型登录:
public class login
{
[required(ErrorMessage ="Please enter your email")]
[display(Name ="Enter email:")]
public string email { get; set; }
[required(ErrorMessage = "Please enter your Password")]
[display(Name = "Enter Password:")]
[DataType(DataType.Password)]
public string password { get; set; }
}
解决方法
EntityType
login
没有定义键。定义此EntityType的密钥。
很显然,您的模型没有键属性,请按如下所示更改login
模型:
public class login
{
[Key]
public int Id {get; set;}
[Required(ErrorMessage ="Please enter your email")]
[Display(Name ="Enter email:")]
public string email { get; set; }
[Required(ErrorMessage = "Please enter your Password")]
[Display(Name = "Enter Password:")]
[DataType(DataType.Password)]
public string password { get; set; }
}
,此错误将解决。 祝你好运。