如题,想问问有没有哪位大神有些这类型的小Demo,想学习学习~~~
你要自己做东西?
想做一个小的管理系统练习练习
public class MongoDbBase
{
public ObjectId _id { get; set; }
}
public class StoreBase<T> where T : MongoDbBase
{
protected readonly static IQueryable<T> LinqQuery;
protected readonly static MongoCollection<T> Collection;
static StoreBase()
{
var mongoUrl = new MongoUrl("mongodb://127.0.0.1:27017");
var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
if (!clientSettings.WriteConcern.Enabled)
{
clientSettings.WriteConcern.W = 1; // ensure WriteConcern is enabled
regardless of what the URL says
}
string collectionName = typeof(T).Name;
var client = new MongoClient(clientSettings);
var server = client.GetServer();
var db = server.GetDatabase("WebApi");
Collection = db.GetCollection<T>(collectionName);
LinqQuery = Collection.AsQueryable();
}
/// <summary>
/// 获取所有元素
/// </summary>
public IEnumerable<T> GetAll()
{
return Collection.FindAll();
}
/// <summary>
/// 根据Id获取一个元素
/// </summary>
public T Get(ObjectId id)
{
return Collection.FindOneById(id);
}
/// <summary>
/// 插入一个元素
/// </summary>
public T Add(T item)
{
if (Collection.Insert(item).Ok)
{
return item;
}
throw new MongoException("往MongoDb插入失败");
}
/// <summary>
/// 根据ID删除元素
/// </summary>
public void Remove(ObjectId id)
{
Collection.Remove(Query.EQ("_id", id));
}
public long RemoveAll()
{
long rt=Collection.Count();
Collection.RemoveAll();
return rt;
}
/// <summary>
/// 局部更新
/// 当字段存在时更新字段,不存在时添加新字段
/// </summary>
public bool Update(ObjectId id, object pms)
{
return
Collection.Update(Query.EQ("_id", id),
new UpdateDocument { { "$set", new QueryDocument {pms.ToBsonDocument() } } }).Ok;
}
/// <summary>
/// 保存修改
/// 当ID不存在时创建新行,存在时更新旧数据
/// </summary>
public bool Save(T doc)
{
return Collection.Save(doc).Ok;
}
引用MongoDB.Bson和MongoDB.Driver这2个文件
然后让你自己的实体类继承MongoDbBase
例子
public class LogModel:MongoDbBase
{
public DateTime CreateTime { get; set; }
public string Lv { get; set; }
/// <summary> 终端编号 </summary>
public string TerminalID { get; set; }
/// <summary> 错误信息 </summary>
public string Msg { get; set; }
}
public class LogStore:StoreBase<LogModel>
{
public void Error(string terminalID, string msg)
{
Add(new LogModel
{
Lv = "Error",
TerminalID = terminalID,
Msg = msg
});
}
public void Info(string terminalID, string msg)
{
Add(new LogModel
{
Lv = "Info",
TerminalID = terminalID,
Msg = msg
});
}
}
@吴瑞祥: 谢谢,不过这个不是我想要的,我想要的是一个完整的案例。。。