MongoDB在Asp .Net Core中的配置
【摘要】 编程语言: c#数据库: MongoDB框架: ASP.Net Core 3.1关于.Net Core的安装,参考:https://dotnet.microsoft.com/download关于mongoDB安装,参考:http://3ms.huawei.cn/km/blogs/details/7923543?l=zh-cn安装程序包:MongoDB.Driver配置文件设置:appset...
编程语言: c#
数据库: MongoDB
框架: ASP.Net Core 3.1
关于.Net Core的安装,参考:
安装程序包:
MongoDB.Driver
配置文件设置:
appsettings.Development.json
"StackDatabaseSettings": {
"CollectionName": "StackRows",
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "StackRowsDb"
}
数据库配置参数接口:
public interface IStackDatabaseSettings
{
string CollectionName { get; set; }
string ConnectionString { get; set; }
string DatabaseName { get; set; }
}
public class StackDatabaseSettings : IStackDatabaseSettings
{
public string CollectionName { get; set; }
public string ConnectionString { get; set; }
public string DatabaseName { get; set; }
}
Startup:
public void ConfigureServices(IServiceCollection services)
services.Configure<StackDatabaseSettings>(Configuration.GetSection(nameof(StackDatabaseSettings)));
services.AddSingleton<IStackDatabaseSettings>(sp =>
sp.GetRequiredService<IOptions<StackDatabaseSettings>>().Value);
}
使用:
StackService
public class StackService
{
private readonly IMongoCollection<Row> _rows;
public StackService(IStackDatabaseSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_rows = database.GetCollection<Row>(settings.CollectionName);
}
public List<Row> Get() =>
_rows.Find(Row => true).ToList();
public Row Get(string id) =>
_rows.Find<Row>(Row => Row.Id == id).FirstOrDefault();
public Row Create(Row Row)
{
_rows.InsertOne(Row);
return Row;
}
public void Update(string id, Row RowIn) =>
_rows.ReplaceOne(Row => Row.Id == id, RowIn);
public void Remove(Row RowIn) =>
_rows.DeleteOne(Row => Row.Id == RowIn.Id);
public void Remove(string id) =>
_rows.DeleteOne(Row => Row.Id == id);
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)