I have a reservation and a ship class for the DB with the Ship and Reservations navigation properties,
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; }
}
The DBcontext.cs file:
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; }
}
}
The reason why I added this line that generates the error and the executeSqlRawAsync methods below is that I tried to solve this error: Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'Ships' when IDENTITY_INSERT is set to OFF.` I want to create a reservation in the DB with a ship in it but I can not insert a value. So I tried fix it with this ValueGeneragtedNever method and the executeRawSql methods but it gives me the error in the title.
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");
}
Any ideas what did I miss?
CodePudding user response:
fix the reservation class , remove [DatabaseGenerated(DatabaseGeneratedOption.None)] and constructor
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; }
}
and since you are using ef core 5 remove all fluent API from dbcontext, you don't need them
and try to add a new item using this code
public async Task CreateReservation(ReservationGetDTO reservationDTO)
{
_context.Reservations.Add(Mapper.Map(reservationDTO, new Reservation()));
await _context.SaveChangesAsync();
}