将数据插入数据库时出错。我的数据库列是:
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; }
}
答案 0 :(得分:0)
此SO有三种不同的解决方案可以帮助您:
How not persist property EF4 code first?
要点:
首先尝试DataAnnotations方法:
确保包含所需的库。然后将[Not Mapped]注释应用于模型中的字段。
using System.ComponentModel.DataAnnotations;
[NotMapped]
public string confirmPassword { get; set; }
如果不这样做,请尝试在dbContext中修改OnModelBuilding方法。这个块有两个选项。第一种是使用Ignore方法。
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<MetaDataUser>().Ignore(p => p.confirmPassword);
}
}
第二种是手动重新映射模型构建并排除字段。
可能有用的其他SO答案:
Entity Framework Code First - How to ignore a column when saving
Exclude a field/property from the database with Entity Framework 4 & Code-First
关于如何手动将属性映射到数据库字段的MS Doc:
https://docs.microsoft.com/en-us/ef/core/modeling/relational/columns
提供答案的简洁示例:
答案 1 :(得分:0)
我认为您需要做的是为页面添加一个viewmodel。首先,您将拥有从实体框架生成的模型,如下所示。
public class UserViewModel
{
public int id{get;set;}
[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; }
}
现在为View创建一个viewModel。这可能如下所示。
[HttpPost]
public ActionResult AddUser(UserViewModel model)
{
User user=new User();
user.username=model.username;
user.password=model.password;
db.User.Add(user);
}
现在在你的控制器动作方法中。你可以这样做。
data(
[
{
"CCODE": "15ET",
"CNAME": "JOE",
"CAGE": 32
},{
"CCODE": "15ET",
"CNAME": "JOE",
"CAGE": 32
},{
"CCODE": "15ET",
"CNAME": "JOE",
"CAGE": 32
}
]
)
希望它有所帮助!