首页 新闻 会员 周边 捐助

跪求使用MongoDB数据库的C#实例,要B/S的~~~~

0
悬赏园豆:40 [待解决问题]

如题,想问问有没有哪位大神有些这类型的小Demo,想学习学习~~~

HXY3377的主页 HXY3377 | 初学一级 | 园豆:128
提问于:2014-02-13 14:08
< >
分享
所有回答(2)
0

你要自己做东西?

[秦时明月] | 园豆:738 (小虾三级) | 2014-02-13 14:15

想做一个小的管理系统练习练习

支持(0) 反对(0) HXY3377 | 园豆:128 (初学一级) | 2014-02-13 14:16
0

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;
}

吴瑞祥 | 园豆:29449 (高人七级) | 2014-02-14 09:53

引用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
    });
  }
}

支持(0) 反对(0) 吴瑞祥 | 园豆:29449 (高人七级) | 2014-02-14 09:56

@吴瑞祥: 谢谢,不过这个不是我想要的,我想要的是一个完整的案例。。。

支持(0) 反对(0) HXY3377 | 园豆:128 (初学一级) | 2014-02-14 11:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册