【发布时间】:2018-10-29 02:27:11
【问题描述】:
将数据插入数据库时出现错误。我的数据库列是:
username, password
我在模型中添加了confirmpassword 来扩展它。
如何在使用具有confirmpassword 属性的模型时摆脱confirmpassword 以插入用户名和密码?
我的代码:
BootstrapTrainingEntities db = new BootstrapTrainingEntities();
var u = new User();
u.username = user.username;
u.password = user.password;
// how to I remove or ignore the confirmPassword property when saving?
db.Users.Add(u);
db.SaveChanges();
型号
[MetadataType(typeof(metadataUser))]
public partial class User
{
public string confirmPassword { get; set; }
}
public class metadataUser
{
[Required(ErrorMessage = "Username is required", AllowEmptyStrings = false)]
[Display(Name ="Username")]
public string username { get; set; }
[Required(ErrorMessage ="Password is required", AllowEmptyStrings = false)]
[Display(Name = "Password")]
[DataType(DataType.Password)]
public string password { get; set; }
[Required(ErrorMessage ="Confirmation Password is required", AllowEmptyStrings = false)]
[Display(Name ="Confiramation Password")]
[DataType(DataType.Password)]
[Compare("password",ErrorMessage = "Password does not match")]
public string confirmPassword { get; set; }
}
【问题讨论】:
-
为什么确认密码字段是架构的一部分?当然这是一个仅限应用程序的东西,你不需要存储它吗?也许您只需要一个独立于 DB 模型的应用程序视图模型,就像大多数 MVC 应用程序的设计方式一样。
-
我扩展了模型。让我编辑我的帖子,生病添加我的模型。请检查一下。谢谢
-
我同意@ADyson,看来您需要拆分数据和视图模型,然后您可以使用确认密码发布视图模型并使用它来填充正确的数据模型数据。
-
我还想到您曾经能够在您希望忽略的属性上使用 [NotMapped] 数据注释,但我不确定这仍然有效,我认为拆分模型是一个更好的主意。
-
"我扩展了模型"...我知道你做到了,但为什么呢?您不需要将该值存储在数据库中,这只是重复。了解如何使用 ViewModel 类将数据库数据与视图数据分开。然后,您可以在视图上拥有与数据库中不同的字段,或者将不同的数据库表组合到一个视图中,等等。更加灵活。
标签: asp.net-mvc entity-framework-6