简体   繁体   English

如何使用 Blazor 和 EF 为导航属性增加价值?

[英]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,我有一个带有 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; }
    }

The DBcontext.cs file: 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; }
    }
}

The reservationController.cs on the sever side:服务器端的reservationController.cs:

        [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:客户端的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;
        }

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.当我按下提交预订按钮并调用 HandleSubmit 函数时,我收到以下错误: 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();我也试过这个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.如果我理解正确,那么默认命名约定将ship id 属性用作EF 的索引,如果您首先将其设置为代码。
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 .我会尝试将此属性设置为其类型的默认值(0 表示intnull表示字符串等)——它应该允许 EF 将它插入到数据库中——如果你想实际添加一个ship这可以工作。
If there is no ship in newly created entity, than just set ship to null - should do the trick.如果新创建的实体中没有船,那么只需将船设置为null - 应该可以解决问题。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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