简体   繁体   中英

How to add value to a navigation property with Blazor and EF?

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; }
        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);
        }

        public DbSet<Reservation> Reservations { get; set; }
        public DbSet<Ship> Ships { get; set; }
    }
}

The reservationController.cs on the sever side:

        [HttpPost]
        public async Task<IActionResult> CreateReservation(ReservationGetDTO reservationDTO) {
            _context.Reservations.Add(Mapper.Map(reservationDTO, new Reservation()));
            await _context.SaveChangesAsync();
            return await GetReservations();
        }

The reservationService.cs on the client side:

        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;
        }

And the razor page that uses this service:

@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);
    }

When I press the submit reservation button and the HandleSubmit function is called I got the following error: Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert explicit value for identity column in table 'Ships' when IDENTITY_INSERT is set to OFF. So I tried this:

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; }

I also tried this modelBuilder.Entity<Reservation>().Property(a => a.Ship).ValueGeneratedNever(); But I got an error that said the ship is a navigation property so i cant use this function

Any ideas?

If I understood you correctly, then ship id property is used as an index by EF by default naming convention, if you set it as code first.
I would try to set this property to a default value of it's kind (0 for int , null for string, etc) - it should allow EF to insert it into the database - this works if you want to actually add a ship .
If there is no ship in newly created entity, than just set ship to null - should do the trick.

我没有工作的原因是我试图在客户端为导航属性添加一个值,而您只能在服务器端执行此操作

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM