1.如何在.Net Core上安裝MongoDB,完全不用擔心直接有套件可以支援MongoDB真是太佛心下列安裝方法均可
a.
MongoDB官網
b.
Nuget
2.如何使用
a.建立Model
public class StaffInfo
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public int age { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Local)]
public DateTime birthday { get; set; }
public string remark { get; set; }
public int likenumber { get; set; }
}
b.宣告Interface
public interface IStaffInfoService
{
List Get();
void Insert( StaffInfo model);
void Update( StaffInfo model);
void Delete(StaffInfo model);
}
c.建立Service寫CURD
public class StaffInfoService : IStaffInfoService
{
private readonly IMongoCollection _staffinfo;
public StaffInfoService()
{
var client = new MongoClient("mongodb://localhost:27017");
//var client = new MongoClient("mongodb://{username}:{password}@{host}:{port}/{Database}")
var database = client.GetDatabase("dbname");
_staffinfo = database.GetCollection("tablename");
}
public void Delete(StaffInfo model)
{
_staffinfo.DeleteOne(x => x.Id == model.Id);
}
public List Get()
{
return _staffinfo.Find(StaffInfo => true).ToList();
}
public void Insert(StaffInfo model)
{
_staffinfo.InsertOne(model);
}
public void Update(StaffInfo model)
{
_staffinfo.ReplaceOne(x => x.Id == model.Id, model);
}
}
d.DI注入即可使用
參考來源
使用 ASP.NET Core 與 MongoDB 建立 Web API