我有一個帶有 Ship 和 Reservations 導航屬性的 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();但是我得到一個錯誤說這艘船是一個導航屬性所以我不能使用這個功能
有任何想法嗎?
uj5u.com熱心網友回復:
如果我理解正確,那么ship默認命名約定將id 屬性用作 EF 的索引,如果您首先將其設定為代碼。
我會嘗試將此屬性設定為其型別的默認值(0 表示int、null表示字串等)——它應該允許 EF 將其插入到資料庫中——如果你想實際添加一個ship.
如果新創建的物體中沒有船,那么只需將船設定為null- 應該可以解決問題。
uj5u.com熱心網友回復:
我沒有作業的原因是我試圖在客戶端為導航屬性添加一個值,而您只能在服務器端執行此操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359189.html
