我有一个带有"船舶"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; }
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);
}
public DbSet<Reservation> Reservations { get; set; }
public DbSet<Ship> Ships { get; set; }
}
}
服务器端的reservationController.cs:
[HttpPost]
public async Task<IActionResult> CreateReservation(ReservationGetDTO reservationDTO) {
_context.Reservations.Add(Mapper.Map(reservationDTO, new Reservation()));
await _context.SaveChangesAsync();
return await GetReservations();
}
客户端的reservationService.cs:
public async Task<List<ReservationGetDTO>> CreateReservation(ReservationPostDTO reserv) {
var result = await _httpClient.PostAsJsonAsync("api/reservations", reserv);
reservations = await result.Content.ReadFromJsonAsync<List<ReservationGetDTO>>();
return reservations;
}
使用此服务的剃须刀页面:
@code {
[Parameter]
public ShipDTO SelectedShip { get; set; }
private ReservationPostDTO reservation = new ReservationPostDTO {
FromDate = DateTime.Today,
ToDate = DateTime.Today.AddDays(1),
};
async void HandleSubmit() {
reservation.Ship = SelectedShip;
await ReservationService.CreateReservation(reservation);
}
当我按下提交预订按钮并调用HandleSubmit函数时,我得到了以下错误:Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'Ships' when IDENTITY_INSERT is set to OFF.
所以我尝试了这个:
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");
}
//I also tried to put this annotation to the Ship
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Ship Ship { get; set; }
我也试过这个modelBuilder.Entity<Reservation>().Property(a => a.Ship).ValueGeneratedNever();
,但我得到了一个错误,说船是一个导航属性,所以我不能使用这个功能
有什么想法吗?
如果我理解正确,那么如果您先将ship
id属性设置为代码,则根据默认命名约定,它将被EF用作索引
我会尝试将此属性设置为其类型的默认值(0表示int
,null
表示字符串等(-它应该允许EF将其插入数据库中-如果您想实际添加ship
,则此操作有效
如果在新创建的实体中没有发货,那么只需将发货设置为null
即可。
我没有工作的原因是我试图在客户端向导航属性添加一个值,而这只能在服务器端上完成