我有一个带有"船舶"one_answers"预订"导航属性的DB的预订和船舶类别,
public class Reservation {
public Reservation() {
Ship = new Ship();
}
public int Id { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Ship Ship { get; set; }
}
public class Ship {
public int Id { get; set; }
public string Name { get; set; }
public string Port{ get; set; }
public List<Reservation> Reservations { get; set; }
}
DBcontext.cs文件:
protected override void OnModelCreating(ModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Reservation>().HasOne(r => r.Ship).WithMany(s => s.Reservations);
modelBuilder.Entity<Reservation>().HasOne(u => u.Person).WithMany(r => r.Reservations);
modelBuilder.Entity<Ship>().HasMany(res => res.Reservations).WithOne(s => s.Ship);
//This line generates the error
modelBuilder.Entity<Reservation>().Property(a => a.Ship).ValueGeneratedNever();
}
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Ship> Ships { get; set; }
}
}
我之所以添加这一行来生成错误并执行下面的SqlRawAsync方法,是因为我试图解决此错误:Microsoft.Data.SqlClient.SqlException(0x80131904(:当identity_insert设置为OFF时,无法在表"Ships"中为标识列插入显式值。"我想在DB中创建一个包含ship的保留,但无法插入值。"。所以我试着用这个ValueGeneratedNever方法和executeRawSql方法来修复它,但它在标题中给了我错误。
public async Task CreateReservation(ReservationGetDTO reservationDTO)
{
await _context.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Reservations] ON");
_context.Reservations.Add(Mapper.Map(reservationDTO, new Reservation()));
await _context.SaveChangesAsync();
await _context.Database.ExecuteSqlRawAsync("SET IDENTITY_INSERT [dbo].[Reservations] OFF");
}
你知道我错过了什么吗?
修复保留类,删除[DatabaseGenerated(DatabaseGeneratedOption.None(]和构造函数
public class Reservation {
public int Id { get; set; }
public DateTime FromDate { get; set; }
public DateTime ToDate { get; set; }
public int ShipId { get; set; }
public virtual Ship Ship { get; set; }
}
public class Ship {
public int Id { get; set; }
public string Name { get; set; }
public string Port{ get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
由于您正在使用ef-core5+从dbcontext中删除所有流畅的API,因此您不需要它们
并尝试使用此代码添加新项目
public async Task CreateReservation(ReservationGetDTO reservationDTO)
{
_context.Reservations.Add(Mapper.Map(reservationDTO, new Reservation()));
await _context.SaveChangesAsync();
}
这不起作用的另一个原因是,在按下提交按钮后,我试图为客户端的导航属性添加值。但您只能在服务器端为导航属性添加值。