.NET和MongoDB之间数据访问的最佳方法 [英] Best approach to the data access between .NET and MongoDB

查看:81
本文介绍了.NET和MongoDB之间数据访问的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我是 一个非常熟悉MongoDB的.net开发人员,如果有人可以分享从MongoDB访问数据的最佳方法/模式,我将不胜感激。


我们正在进行POC项目,MongoCollection领域正在改变经常。


由于我们正在使用RepositoryPattern,因此每次添加MongoDB数据库时我们都需要对我们的实体进行更改。


有没有人遇到过这样的问题,是否有更好的方法可以从.NET中的MongoDB进行数据访问。


由于MongoDB是无模式的, 它可以有更少的字段或所有字段取决于数据。


请分享任何代码片段或我们参考。


感谢您的帮助



谢谢,



解决方案

您好techasuran,


>>请分享任何代码段或我们参考。


您可以使用MongoDB C#驱动程序访问MongoDB。您可以连接到MongoDB并执行CURD操作。以下示例代码供您参考。

使用 系统;    
使用  System.Collections.Generic;   
使用  System.Linq;   
使用  System.Text;   
使用  System.Timers;   
使用  MongoDB.Bson;   
使用  MongoDB.Driver;   
使用  MongoDB.Driver.Builders;   
使用  MongoDB.Driver.GridFS;   
使用  MongoDB.Driver.Linq;   
使用  System.Data.SqlClient;   
名称空间  MongodbRND   
{   
    class  Program   
    {   
       static  void  Main(string []  args)   
       {   
          Console.WriteLine(QUOT;蒙戈  DB 试验 申请表]);   
          Console.WriteLine(" ====================== ==============================");   
          Console.WriteLine(" Started  By:Kailash  Chandra  Behera");   
          Console.WriteLine(QUOT;开始  ON:  14  7月  2014");   
          Console.WriteLine(" Configuration  Setting:  172.16.1.24:27017");   
          Console.WriteLine(" ====================== ==============================");   
          Console.WriteLine(" Initializaing  connection");   
          string  connectionString  = " mongodb://172.16.1.24:27017";   
  
  
          Console.WriteLine(" Creating  Client ..........");     ;
          MongoClient  client  =  null;   
          try   
          {   
             client  =  new  MongoClient(connectionString);   
             Console.WriteLine(QUOT;客户 创建  Successfuly ........") ;   
             Console.WriteLine(" Client: "  +  client.ToString() );   
         }   
          catch (例外  ex)   
          {   
             Console.WriteLine(QUOT;提起 至 创建 客户......." );   
             Console.WriteLine(ex.Message);   
         }   
  
          Console.WriteLine(QUOT; Initianting 蒙戈  Db的 服务器.......");    
          MongoServer  server  =  null;   
          try   
          {   
             Console.WriteLine(QUOT;获取 服务机构 对象......");&NBSP ;  
             server  =  client.GetServer();   
  
             Console.WriteLine(QUOT;服务器 对象 创建 成功....");&NBSP ;  
             Console.WriteLine(QUOT;服务器 :"  +  server.ToString()) ;   
         }   
          catch (例外  ex)   
          {   
             Console.WriteLine(" Filed  to nbsp;  Server  Details");    
             Console.WriteLine(ex.Message);   
         }   
  
  
          Console.WriteLine(" Initianting  Mongo  Databaser .........");    
          MongoDatabase  database  =  null;   
          try   
          {   
             Console.WriteLine("   of nbsp; of database ......." );   
             database  =  server.GetDatabase(" Kailash");   
             Console.WriteLine(QUOT;数据库 名称 : "  + 数据库。名称);   
         }   
          catch (例外  ex)   
          {   
             Console.WriteLine(QUOT;失败 至 获取 参考 的 数据库");    
             Console.WriteLine(QUOT;错误 :"  +  ex.Message);&NBSP ;  
         }   
          try   
          {   
             Console.WriteLine(QUOT; delete一个 收集和NBSP;符号与QUOT;);   
             database.DropCollection(" Symbol");   
         }   
          catch (例外  ex)   
          {   
             Console.WriteLine(QUOT;失败 至 删除 收集 从 数据库");    
             Console.WriteLine(QUOT;错误 :"  +  ex.Message);&NBSP ;  
         }   
  
          Console.WriteLine(" Getting  Collections  from the nbsp; database  Database .......");    
  
  
          MongoCollection  symbolcollection  =  null;   
          try   
          {   
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; symbolcollection&NBSP; =&NBSP; database.GetCollection<符号与GT;("符号");&NBSP;&NBSP; &NBSP;
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Console.WriteLine(symbolcollection.Count()的ToString());&NBSP;&NBSP;&NBSP;
         }   
          catch (例外  ex)   
          {   
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Console.WriteLine("失败&NBSP;到&NBSP;获取&NBSP;收缴&NBSP;从&NBSP;数据库");&NBSP; &NBSP;&NBSP;
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Console.WriteLine(QUOT;错误 :"&NBSP; +&NBSP; ex.Message);&NBSP ;&NBSP;&NBSP;
         }   
          ObjectId  id  =  new  ObjectId();   
          Console.WriteLine(" Inserting  document  to nbsp; collection ............") ;&NBSP;&NBSP;&NBSP;
          try   
          {   
             Symbol  symbol  =  new  Symbol ();   
             symbol.Name  = "Star";   
             symbolcollection.Insert(symbol);   
             id  =  symbol.ID;   
  
             Symbol  symbol  =  new  Symbol ();   
             symbol.Name  = "Star1";   
             symbolcollection.Insert(symbol);   
             id  =  symbol.ID;   
  
             Console.WriteLine(symbolcollection.Count()。ToString());   
         }   
          catch (例外  ex)   
          {   
             Console.WriteLine("&fbsp  to   into  collection  of nbsp;  " &NBSP; +&NBSP; database.Name);&NBSP;&NBSP;&NBSP;
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Console.WriteLine(QUOT;错误 :"&NBSP; +&NBSP; ex.Message);&NBSP ;&NBSP;&NBSP;
         }   
  
          try   
          {   
             Console.WriteLine(" Preparation  Query  Document ............ ");&NBSP;&NBSP;&NBSP;
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;列表与LT;&NBSP;符号&NBSP;>&NBSP;查询&NBSP; =&NBSP; symbolcollection.AsQueryable<实体>( )。凡<实体>(SB&NBSP; =>&NBSP; sb.Name&NBSP; ==&NBSP;"凯拉什")ToList();&NBSP;&NBSP;&NBSP;
  
            Symbol  symbol  =  symbolcollection.AsQueryable< Entity>()。Where< Entity>(sb  ; =>&NBSP; SB&NBSP; ID&NBSP; ==&NBSP; ID).ToList();&NBSP;&NBSP;&NBSP;
  
         }   
          catch (例外  ex)   
          {   
             Console.WriteLine("&fons  to  from  collection");   &NBSP;
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP; Console.WriteLine(QUOT;例外&NBSP;:"&NBSP; +&NBSP; ex.Message);&NBSP ;&NBSP;&NBSP;
         }   
          Console.WriteLine("");   
          Console.WriteLine(" ====================== ==============================");&NBSP;&NBSP;&NBSP;
          Console.ReadLine();   
      }   
   }   
    public  class  Symbol   
    {   
       public  string  Name  {  get;  set; }   
       public  ObjectId  ID  {  get;  set; }   
   }   

有关详细信息,请参阅:


http://www.c-sharpcorner.com/UploadFile/87b416/getting-started-mongodbwithcsharp/


此外,使用MongoDB与在LINQ和Entity Framework中工作相同。 MongoDB包含与LINQ相同的功能和相同的工作方式。有关详细信息,请参阅:


https:/ /www.cdata.com/kb/tech/mongodb-ado-codefirst.rst


#EF Core


https://www.codeproject.com/Articles/1151842/Using-MongoDB -NET-Driver-with-NET-Core-WebAPI


祝你好运,


Cole Wu


Hi All,

I am  a .net developer quite new to MongoDB, I would appreciate if anybody can share the best approach / pattern to access data from MongoDB.

We were doing POC project and the MongoCollection field were changing based frequently.

Since we are using the RepositoryPattern, Because of this every time when the MongoDB feilds get added we need to make changes for our entities.

Has anybody ever faced any issues like this and is there any better approach for data access from MongoDB in .NET.

Since MongoDB is schema-less,  it can have have less fields or all the fields depends on the data.

Please share any code snippets or we reference.

Appreciate your help

thanks,

解决方案

Hi techasuran,

>>Please share any code snippets or we reference.

you could use MongoDB C# driver to access MongoDB. which you could connect to MongoDB and execute CURD operation. the following sample code for your reference.

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Text;    
using System.Timers;    
using MongoDB.Bson;    
using MongoDB.Driver;    
using MongoDB.Driver.Builders;    
using MongoDB.Driver.GridFS;    
using MongoDB.Driver.Linq;    
using System.Data.SqlClient;    
namespace MongodbRND    
{    
   class Program    
   {    
      static void Main(string[] args)    
      {    
         Console.WriteLine("Mongo DB Test Application");    
         Console.WriteLine("====================================================");    
         Console.WriteLine("Started By:Kailash Chandra Behera");    
         Console.WriteLine("Started On: 14 July 2014");    
         Console.WriteLine("Configuration Setting: 172.16.1.24:27017");    
         Console.WriteLine("====================================================");    
         Console.WriteLine("Initializaing connection");    
         string connectionString = "mongodb://172.16.1.24:27017";    
   
   
         Console.WriteLine("Creating Client..........");    
         MongoClient client = null;    
         try    
         {    
            client = new MongoClient(connectionString);    
            Console.WriteLine("Client Created Successfuly........");    
            Console.WriteLine("Client: " + client.ToString());    
         }    
         catch (Exception ex)    
         {    
            Console.WriteLine("Filed to Create Client.......");    
            Console.WriteLine(ex.Message);    
         }    
   
         Console.WriteLine("Initianting Mongo Db Server.......");    
         MongoServer server = null;    
         try    
         {    
            Console.WriteLine("Getting Servicer object......");    
            server = client.GetServer();    
   
            Console.WriteLine("Server object created Successfully....");    
            Console.WriteLine("Server :" + server.ToString());    
         }    
         catch (Exception ex)    
         {    
            Console.WriteLine("Filed to getting Server Details");    
            Console.WriteLine(ex.Message);    
         }    
   
   
         Console.WriteLine("Initianting Mongo Databaser.........");    
         MongoDatabase database = null;    
         try    
         {    
            Console.WriteLine("Getting reference of database.......");    
            database = server.GetDatabase("Kailash");    
            Console.WriteLine("Database Name : " + database.Name);    
         }    
         catch (Exception ex)    
         {    
            Console.WriteLine("Failed to Get reference of Database");    
            Console.WriteLine("Error :" + ex.Message);    
         }    
         try    
         {    
            Console.WriteLine("Deleteing Collection Symbol");    
            database.DropCollection("Symbol");    
         }    
         catch (Exception ex)    
         {    
            Console.WriteLine("Failed to delete collection from Database");    
            Console.WriteLine("Error :" + ex.Message);    
         }    
   
         Console.WriteLine("Getting Collections from database Database.......");    
   
   
         MongoCollection symbolcollection = null;    
         try    
         {    
            symbolcollection = database.GetCollection<Symbol>("Symbols");    
            Console.WriteLine(symbolcollection.Count().ToString());    
         }    
         catch (Exception ex)    
         {    
            Console.WriteLine("Failed to Get collection from Database");    
            Console.WriteLine("Error :" + ex.Message);    
         }    
         ObjectId id = new ObjectId();    
         Console.WriteLine("Inserting document to collection............");    
         try    
         {    
            Symbol symbol = new Symbol ();    
            symbol.Name = "Star";    
            symbolcollection.Insert(symbol);    
            id = symbol.ID;    
   
            Symbol symbol = new Symbol ();    
            symbol.Name = "Star1";    
            symbolcollection.Insert(symbol);    
            id = symbol.ID;    
   
            Console.WriteLine(symbolcollection.Count().ToString());    
         }    
         catch (Exception ex)    
         {    
            Console.WriteLine("Failed to insert into collection of Database " + database.Name);    
            Console.WriteLine("Error :" + ex.Message);    
         }    
   
         try    
         {    
            Console.WriteLine("Preparing Query Document............");    
            List< Symbol > query = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb.Name == "Kailash").ToList();    
   
            Symbol symbol = symbolcollection.AsQueryable<Entity>().Where<Entity>(sb => sb. ID == id).ToList();    
   
         }    
         catch (Exception ex)    
         {    
            Console.WriteLine("Failed to query from collection");    
            Console.WriteLine("Exception :" + ex.Message);    
         }    
         Console.WriteLine("");    
         Console.WriteLine("====================================================");    
         Console.ReadLine();    
      }    
   }    
   public class Symbol    
   {    
      public string Name { get; set; }    
      public ObjectId ID { get; set; }    
   }    
} 

For more information, please refer to:

http://www.c-sharpcorner.com/UploadFile/87b416/getting-started-mongodbwithcsharp/

In addition, Working with MongoDB is the same as working in LINQ and Entity Framework. MongoDB contains the same features and the same work style that LINQ has. For more information, please refer to:

https://www.cdata.com/kb/tech/mongodb-ado-codefirst.rst

#EF Core

https://www.codeproject.com/Articles/1151842/Using-MongoDB-NET-Driver-with-NET-Core-WebAPI

Best regards,

Cole Wu


这篇关于.NET和MongoDB之间数据访问的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆