[英]Entity Framework one to one relationship error
I am trying to save a sale in the database, the sale has a user, when I saved the first sale with the code that I attached I had no problem, but from there, every time I went to save another resulting sale in the following Error:我正在尝试将销售保存在数据库中,销售有一个用户,当我使用附加的代码保存第一次销售时我没有问题,但是从那里,每次我去保存另一个结果销售时错误:
Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'
SqlException: Cannot insert duplicate key row in object 'dbo.sale' with unique index 'IX_sale_userId'. The duplicate key value is (2). The statement has been terminated.
What am I doing wrong?我究竟做错了什么?
Sale Form: private void button2_Click(object sender, EventArgs e) {销售形式:private void button2_Click(object sender, EventArgs e) {
using (var context = new AppDbContext())
{
sale V = new sale();
V.date = DateTime.Today.Date;
V.userId = 2;
context.Add(V);
context.SaveChanges();
}
} }
Sale:销售:
public class sale
{
[Key]
public int saleId { get; set; }
public DateTime date { get; set; }
public int userId { get; set; }
public virtual user user { get; set; }
}
User:用户:
public class user
{
[Key]
public int useroId { get; set; }
public string nape { get; set; }
public string surname { get; set; }
public string email { get; set; }
public string password { get; set; }
public virtual sale sale { get; set; }
}
AppDBContext:应用数据库上下文:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<sale>().HasOne(a => a.user);
base.OnModelCreating(modelBuilder);
}
Try the following fluent Mapping尝试以下流畅的映射
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<sale>()
.HasOne(a => a.user)
.WithOne(b => b.sale)
.HasForeignKey<user>(b => b.userId);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.