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 { Listc.建立Service寫CURDGet(); void Insert( StaffInfo model); void Update( StaffInfo model); void Delete(StaffInfo model); }
public class StaffInfoService : IStaffInfoService { private readonly IMongoCollectiond.DI注入即可使用_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); } }
參考來源
使用 ASP.NET Core 與 MongoDB 建立 Web API