试图在User
和Artist
之间建立一对零关系,并选择ArtistId
作为主键和外键,但是在插入数据时,数据库不会让我
错误
Cannot insert explicit value for identity column in table 'Artists' when IDENTITY_INSERT is set to OFF
模型
public class User
{
[Key]
public int UserId { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[MinLength(3)]
[MaxLength(255)]
public string Password { get; set; }
[Required]
public byte RoleId { get; set; }
public DateTime RegisterDate { get; set; }
public Artist Artist { get; set; }
}
public class Artist
{
[ForeignKey("User")]
public int ArtistId { get; set; }
public string ProfilePhoto { get; set; }
public string Bio { get; set; }
public User User { get; set; }
}
控制器中的动作
public ActionResult Register(ArtistRegisterViewModel viewModel)
{
if (ModelState.IsValid)
{
if (viewModel.ConfirmPassword == viewModel.User.Password)
{
var user = new User
{
Email = viewModel.User.Email,
Password = viewModel.User.Password,
RegisterDate = DateTime.Now,
RoleId = RoleType.Artist
};
var artist = new Artist
{
Bio = viewModel.Artist.Bio,
ProfilePhoto = viewModel.Artist.ProfilePhoto,
};
_context.Users.Add(user);
_context.Artists.Add(artist);
_context.SaveChanges();
return Content("New Artist Created");
}
}
return View("Register", viewModel);
}
答案 0 :(得分:0)
注释ArtistId
,以便EF不会为PK创建身份:
[ForeignKey("User")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ArtistId { get; set; }