Asp.net Core Webapi for MongoDB

标签: Mongodb  Core  c#  asp.net  后端

Asp.net Core Webapi for MongoDB

创建asp.net core webapi 3.1

1、 配置连接字符串

  "BookstoreDatabaseSettings": {
    "BooksCollectionName": "Books",
    "ConnectionString": "mongodb://localhost:27017",
    "DatabaseName": "BookstoreDb"
  },

2、添加实体类

新建一个Models文件夹,添加一个Book实体类

public class Book
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

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

    public decimal Price { get; set; }

    public string Category { get; set; }

    public string Author { get; set; }
}

3、添加Book的操作类

 public class BookstoreDatabaseSettings : IBookstoreDatabaseSettings
 {
     public string BooksCollectionName { get; set; }
     public string ConnectionString { get; set; }
     public string DatabaseName { get; set; }
 }

 public interface IBookstoreDatabaseSettings
 {
     string BooksCollectionName { get; set; }
     string ConnectionString { get; set; }
     string DatabaseName { get; set; }
 }

4、添加services类

 public class BookService
 {
     private readonly IMongoCollection<Book> _books;

     public BookService(IBookstoreDatabaseSettings settings)
     {
         var client = new MongoClient(settings.ConnectionString);
         var database = client.GetDatabase(settings.DatabaseName);

         _books = database.GetCollection<Book>(settings.BooksCollectionName);
     }

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

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

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

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

5、注册服务

在setup.cs ConfigureServices 里面注册服务

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();
}
版权声明:本文为qq_43542583原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_43542583/article/details/104432873