現在要來建立我們專案的後端資料庫與Web API了
首先建立簡單一個Test DB
db.Users.insert([
{UserId:"1",UserName:"Linda"},
{UserId:"2",UserName:"Lue"},
{UserId:"3",UserName:"James",Birthday:"2000/01/01"},
{UserId:"4",UserName:"Webber",Birthday:"1988/01/01"},
{UserId:"5",UserName:"Wade",Birthday:"2010/01/01",Phone: "234-5678"}])
接著開啟地表最強IDE- Visual Studio 2017
再來安裝連接MongoDB的driver
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace TestWebAPI.Models
{
public class User
{
public ObjectId Id { get; set; }
[BsonElement("UserId")]
public string UserId { get; set; }
[BsonElement("UserName")]
public string UserName { get; set; }
[BsonElement("Phone")]
public string Phone { get; set; }
[BsonElement("Birthday")]
public string Birthday { get; set; }
}
}
接著為了我們API回傳的方便
public class Response<T>
{
public bool IsSuccess { get; set; }
public T Data { get; set; }
public string ErrorMessage { get; set; }
}
public class DataAccess
{
MongoClient _client;
MongoServer _server;
MongoDatabase _db;
public DataAccess()
{
_client = new MongoClient("mongodb://localhost:27017");
_server = _client.GetServer();
_db = _server.GetDatabase("testDB");
}
public IEnumerable<User> GetUsers()
{
return _db.GetCollection<User>("Users").FindAll();
}
public User GetUser(ObjectId id)
{
var res = Query<User>.EQ(p => p.Id, id);
return _db.GetCollection<User>("Users").FindOne(res);
}
public User CreateUser(User user)
{
_db.GetCollection<User>("Users").Save(user);
return user;
}
public bool UpdateUser(ObjectId id, User user)
{
user.Id = id;
var res = Query<User>.EQ(u => u.Id, id);
var operation = Update<User>.Replace(user);
var result = _db.GetCollection<User>("Users").Update(res, operation);
return !result.HasLastErrorMessage;
}
public bool RemoveUser(ObjectId id)
{
var res = Query<User>.EQ(e => e.Id, id);
var operation = _db.GetCollection<User>("Users").Remove(res);
return !operation.HasLastErrorMessage;
}
}
}
我們習慣透過Repository
來在Controller與Database中溝通
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestWebAPI.Models;
namespace TestWebAPI.Handler
{
public interface IUserRepository
{
Response<User> AddUser(User u);
Response<IEnumerable<User>> GetAllUser();
Response<bool> DeleteUser(string Id);
Response<User> GetUserById(string Id);
Response<bool> UpdateUser(string Id, User u);
}
}
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TestWebAPI.Models;
namespace TestWebAPI.Handler
{
public class UserRepository : IUserRepository
{
private readonly DataAccess _db;
public UserRepository(DataAccess db)
{
_db = db;
}
public Response<User> AddUser(User u)
{
var result = new Response<User>();
result.IsSuccess = true;
try
{
result.Data = _db.CreateUser(u);
}
catch (Exception ex)
{
result.IsSuccess = false;
result.ErrorMessage = ex.Message;
}
return result;
}
public Response<bool> DeleteUser(string Id)
{
var result = new Response<bool>();
result.IsSuccess = true;
try
{
var objId = new ObjectId(Id);
result.Data = _db.RemoveUser(objId);
}
catch (Exception ex)
{
result.IsSuccess = false;
result.ErrorMessage = ex.Message;
}
return result;
}
public Response<IEnumerable<User>> GetAllUser()
{
var result = new Response<IEnumerable<User>>();
result.IsSuccess = true;
try
{
result.Data = _db.GetUsers();
}
catch (Exception ex)
{
result.IsSuccess = false;
result.ErrorMessage = ex.Message;
}
return result;
}
public Response<User> GetUserById(string Id)
{
var result = new Response<User>();
result.IsSuccess = true;
try
{
var objId = new ObjectId(Id);
result.Data = _db.GetUser(objId);
}
catch (Exception ex)
{
result.IsSuccess = false;
result.ErrorMessage = ex.Message;
}
return result;
}
public Response<bool> UpdateUser(string Id, User u)
{
var result = new Response<bool>();
result.IsSuccess = true;
try
{
var objId = new ObjectId(Id);
result.Data = _db.UpdateUser(objId, u);
}
catch (Exception ex)
{
result.IsSuccess = false;
result.ErrorMessage = ex.Message;
}
return result;
}
}
}
前面建置完成後,最後可以寫Web API了
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using TestWebAPI.Handler;
using TestWebAPI.Models;
namespace TestWebAPI.Controllers
{
[Route("api/user/[action]/")]
public class UserAPIController : Controller
{
private readonly IUserRepository _userRepository;
public UserAPIController(IUserRepository repository)
{
_userRepository = repository;
}
// GET: api/<controller>
[HttpGet]
public Response<IEnumerable<User>> GetAllUser()
{
return _userRepository.GetAllUser();
}
// GET api/<controller>/5
[HttpGet]
public Response<User> GetUserById(string Id)
{
var response = _userRepository.GetUserById(Id);
var s = response.Data.Id.ToString();
return response;
}
// POST api/<controller>
[HttpPost]
public Response<User> AddUser([FromBody]User u)
{
var response = _userRepository.AddUser(u);
return response;
}
[HttpPut]
public Response<bool> UpdateUser(string Id, [FromBody] User u)
{
var response = _userRepository.UpdateUser(Id, u);
return response;
}
// DELETE api/<controller>/5
[HttpDelete]
public Response<bool> DeleteUser(string Id)
{
var response = _userRepository.DeleteUser(Id);
return response;
}
}
}
前置作業大致到這
To be continued