我尝试保存表单记录,我从客户端获取实体,但每次需要PersonalId = 0
,这将是重复的主键错误。
我该如何解决?
public ActionResult SavePersonal(PersonalViewModel model)
{
try
{
StorageSystemEntities1 db = new StorageSystemEntities1();
Personal personal = new Personal();
personal.PName = model.PName;
personal.PLastname = model.PLastname;
personal.PStatus = model.PStatus;
personal.ShopId = model.ShopId;
personal.PPassword = model.PPassword;
personal.GenderID = model.GenderID;
personal.DOB = model.DOB;
personal.Email = model.Email;
personal.JobStartDate = model.JobStartDate;
personal.PAuthorisation = model.PAuthorisation;
personal.Phone = model.Phone;
db.Personal.Add(personal);
db.SaveChanges();
int latestPersonalId = personal.PersonalID;
}
catch (Exception ex)
{
throw ex;
}
return RedirectToAction("_AddPersonal");
}
答案 0 :(得分:0)
很少有办法通过,即:
在您的应用中生成唯一ID(即guid)
同样的事情,但在你的数据库引擎(即sql程序)
使用上一个答案中提到的sql身份,因此在您的应用中不应该做任何事情
希望以上其中一项有帮助
答案 1 :(得分:0)
在[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
课程中使用Personal
。
示例:
public class Personal {
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PersonalId {get;set;}
public string PName {get;set;}
public string PLastname {get;set;}
public string PStatus {get;set;}
public int ShopId {get;set;}
[DataType(DataType.Password)]
public string PPassword {get;set;}
public string GenderID {get;set;}
public DateTime? DOB {get;set;}
[EmailAddress]
public string Email {get;set;}
public DateTime? JobStartDate {get;set;}
public string PAuthorisation {get;set;}
[DataType(DataType.PhoneNumber)]
public string Phone {get;set;}
}