码迷,mamicode.com
首页 > 数据库 > 详细

Asp.net Core Webapi for MongoDB

时间:2020-02-15 13:04:48      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:readonly   basename   EDA   first   字符串   技术   local   tco   mic   

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

Asp.net Core Webapi for MongoDB

标签:readonly   basename   EDA   first   字符串   技术   local   tco   mic   

原文地址:https://www.cnblogs.com/qzdd/p/12311116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!