Ошибка в функции обновления. ASP. Net операция CRUD веб-API ядра 3.0 - PullRequest
0 голосов
/ 14 июля 2020

Я пишу операцию CRUD в ASP. Net core 3.0, веб-API, используя MongoDB в качестве хранилища данных. Я обнаружил ошибку при попытке обновить документ. Я новичок в C#, может кто-нибудь помочь мне это проверить. Заранее спасибо.

Это моя настройка в настройках приложения. json файл

 {
  "BookstoreDatabaseSettings": {
    "BookCollectionName": "Books",
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "BookstoreDB"
  }
}

Это моя служба конфигурации для MongoDB в файле Startup.cs

 public void ConfigureServices(IServiceCollection services)
 {
   services.Configure<BookstoreDatabaseSettings>(
     Configuration.GetSection(nameof(BookstoreDatabaseSettings)));

   services.AddSingleton<IBookstoreDatabaseSettings>(sp =>
     sp.GetRequiredService<IOptions<BookstoreDatabaseSettings>>().Value);

   services.AddSingleton<BookService>();

   services.AddControllers();
 }

Это мой файл BookstoreDatabaseSetting.cs в папке Models

namespace API_Net_Mdb.Models
{
    public class BookstoreDatabaseSettings : IBookstoreDatabaseSettings
    {
        public string BookCollectionName { get; set; }
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }

    public interface IBookstoreDatabaseSettings
    {
        string BookCollectionName { get; set; }

        string ConnectionString { get; set; }

        string DatabaseName { get; set; }
    }
}

Это мой файл Book.cs в папке Model

using Newtonsoft.Json;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace API_Net_Mdb.Models
{
    public class Book
    {
        [BsonId] // designate this as document primary key
        [BsonRepresentation(BsonType.ObjectId)] // this allows passing the parameter as type string instead of an ObjectId structure
        public string Id { get; set; }

        [BsonElement("Name")]
        [JsonProperty("Name")]
        public string Name { get; set; }

        public decimal Price { get; set; }

        public string Category { get; set; }

        public string Author { get; set; }
    }
}

Это мой файл BookServices.cs

using System.Collections.Generic;
using API_Net_Mdb.Models;
using MongoDB.Driver;

namespace API_Net_Mdb.Services
{
    public class BookService
    {
        private readonly IMongoCollection<Book> _books;

        public BookService(IBookstoreDatabaseSettings settings)
        {
            var client = new MongoClient(settings.ConnectionString);
            var db = client.GetDatabase(settings.DatabaseName);
            _books = db.GetCollection<Book>(settings.BookCollectionName);
        }

        public List<Book> Get() => _books.Find(book => true).ToList();

        public Book Get(string id) => _books.Find(book => book.Id == id).FirstOrDefault();

        public Book Create(Book book)
        {
            _books.InsertOne(book);

            return book;
        }
         // This is the update service
        public void Update(string id, Book bookIn) => _books.ReplaceOne(book => book.Id == id, bookIn);

        public void Remove(Book bookIn) => _books.DeleteOne(book => book.Id == bookIn.Id);

        public void Remove(string id) => _books.DeleteOne(book => book.Id == id);
    }
}

Это функция обновления в моем файле BooksController.cs

  [HttpPut("{id:length(24)}")]
  public IActionResult Update(string id, Book bookIn)
  {
    var book = _bookService.Get(id);

    if (book == null)
    {
       return NotFound();
    }
     
    _bookService.Update(id, bookIn);

       return NoContent();
    }

Это ошибка, с которой я столкнулся при тестировании конечной точки обновления в бессоннице

** MongoDB.Driver.MongoWriteException: A write operation resulted in an error.
  After applying the update, the (immutable) field '_id' was found to have been altered to _id: null
 ---> MongoDB.Driver.MongoBulkWriteException`1[API_Net_Mdb.Models.Book]: A bulk write operation resulted in one or more errors.
  After applying the update, the (immutable) field '_id' was found to have been altered to _id: null **

Это это мое тело запроса

{
    "Name": "Understanding Lambda Expression",
    "Price": 16.34,
    "Category": "Programming",
    "Author": "DanielAdek"
}

Пожалуйста, а что я сделал не так?

...