SQL Server combined with MongoDB Nhibernate_mongodb

Source: Internet
Author: User
Tags commit mongoclient mongodb static class create database

This example for you to share the SQL Server and MongoDB use NHibernate code, for your reference, the specific content as follows

Program.cs Code content:

Class Program {Private Const string sqlserverconnectionstring = @ "Data source=.;i Nitial Catalog=sqlwithmongo; Persist Security info=true; User Id=sa; 
 
   password=123456 "; 
   Private Const string mongoconnectionstring = "mongodb://localhost:27017"; 
 
   Private Const int numberofnodes = 1000; 
     private static void Main (string[] args) {Console.WriteLine ("Clearing Database ..."); 
     Cleardatabases (); 
     Initer.init (sqlserverconnectionstring, mongoconnectionstring); 
 
     Console.WriteLine ("Completed"); 
     Console.WriteLine ("Creating Nodes ..."); 
     Create SQL Server node node createnodes (); 
 
     Console.WriteLine ("Completed"); 
     Console.WriteLine ("Linking Nodes ..."); Long milliseconds1 = Linksqlnodes (); 
     Create SQL Server's Linknode node Console.WriteLine ("SQL:" + milliseconds1); Long milliseconds2 = Linkmongonodes (); 
     Also create Node,linknode node Console.WriteLine ("Mongo:" + milliseconds2); 
 
    Console.WriteLine ("Completed"); Console.WriteLine ("Fetching Nodes ..."); Long Milliseconds3 = Fetchsqlnodes (); 
     Remove SQL Server node data Console.WriteLine ("SQL:" + MILLISECONDS3); Long MILLISECONDS4 = Fetchmongonodes (); 
     Remove the MongoDB node data Console.WriteLine ("Mongo:" + milliseconds4); 
 
     Console.WriteLine ("Completed"); 
   Console.readkey (); 
     private static Long Fetchmongonodes () {var stopwatch = new Stopwatch (); Stopwatch. 
 
     Start (); for (int i = 0; i < numberofnodes i++) {using (var unitofwork = new Unitofwork ()) {V 
 
         AR repository = new mongonoderepository (unitofwork); Mongonode node = repository. 
         GetByID (i + 1); Ireadonlylist<nodelink> links = node. 
       Links; }} stopwatch. 
     Stop (); Return stopwatch. 
   Elapsedmilliseconds; 
     private static Long Fetchsqlnodes () {var stopwatch = new Stopwatch (); Stopwatch. 
 
     Start (); for (int i = 0; i < numberofNodes; i++) {using (var unitofwork = new Unitofwork ()) {var repository = new Noderepository (uni 
 
         Tofwork); Node node = repository. 
         GetByID (i + 1); Ireadonlylist<node> links = Node. 
       Links; }} stopwatch. 
     Stop (); Return stopwatch. 
   Elapsedmilliseconds; 
     private static Long Linksqlnodes () {var stopwatch = new Stopwatch (); Stopwatch. 
 
     Start (); 
 
       using (var unitofwork = new Unitofwork ()) {var repository = new Noderepository (unitofwork); ilist<node> nodes = Repository. 
       GetAll (); foreach (node Node1 in nodes) {foreach (node Node2 in nodes) {Node1. 
         Addlink (Node2); 
     } unitofwork.commit (); } stopwatch. 
     Stop (); Return stopwatch. 
   Elapsedmilliseconds; 
     private static Long Linkmongonodes () {var stopwatch = new Stopwatch (); Stopwatch.Start (); 
 
       using (var unitofwork = new Unitofwork ()) {var repository = new Mongonoderepository (unitofwork); ilist<mongonode> nodes = Repository. 
       GetAll (); foreach (Mongonode node1 in nodes) {foreach (Mongonode node2 in nodes) {Node1. 
         Addlink (Node2); 
     } unitofwork.commit (); } stopwatch. 
     Stop (); Return stopwatch. 
   Elapsedmilliseconds; private static void Createnodes () {using (var unitofwork = new Unitofwork ()) {var repo 
 
       Sitory = new Noderepository (unitofwork); for (int i = 0; i < numberofnodes i++) {var node = new node ("node" + (i + 1)); The instantiation constructor initializes the name repository. 
       Save (node); 
     } unitofwork.commit (); 
 
       using (var unitofwork = new Unitofwork ()) {var repository = new Mongonoderepository (unitofwork); for (int i = 0; i < NumBerofnodes; 
         i++) {var node = new Mongonode ("node" + (i + 1)); Repository. 
       Save (node); 
     } unitofwork.commit (); }//Empty data private static void Cleardatabases () {new Mongoclient (mongoconnectionstring). Getdatabase ("Sqlwithmongo"). Dropcollectionasync ("links"). 
 
     Wait (); string query = "DELETE from [dbo]." [Mongonode]; " + "DELETE from [dbo]." [Node_node]; " + "DELETE from [dbo]." [Node]; " + "UPDATE [dbo]." [Ids] 
 
     SET [Nexthigh] = 0 "; using (var connection = new SqlConnection (sqlserverconnectionstring)) {var command = new SqlCommand (query, 
 
       Connection) {CommandType = CommandType.Text}; Connection. 
       Open (); Command. 
     ExecuteNonQuery (); 
 } 
   } 
 }

The related auxiliary class code is as follows:

public static class Initer 
 {public 
   static void Init (String sqlserverconnectionstring, String mongoconnectionstring) 
   { 
     //sqlserver initialization 
     sessionfactory.init (sqlserverconnectionstring); 
     MongoDB initialization 
     Nodelinkrepository.init (mongoconnectionstring); 
   } 
  
public static class Sessionfactory//factory {private static isessionfactory _factory; Internal static ISession Opensession () {return _factory. 
    Opensession (New Interceptor ()); } internal static void Init (String connectionString) {_factory = Buildsessionfactory (Connectionstrin 
    g); private static Isessionfactory Buildsessionfactory (string connectionString) {//configured in a programmatic way to give you a better understanding 
      , there is no need to write a complex mapping file, it can completely replace the nhibernate mapping file, so that you can use C # in the mapping of the strongly typed way. Fluentconfiguration configuration = Fluently.configure (). Database (MsSqlConfiguration.MsSql2012.ConnectionString (ConnectionString)). Mappings (M => m.fluentmappings.addfromassembly (assembly.getexecutingassembly ())). 
          Exposeconfiguration (x => {x.eventlisteners.postloadeventlisteners = new ipostloadeventlistener[) 
        {New EventListener ()}; 
 
      }); return configuration. BuildseSsionfactory (); 
 } 
  }
Internal class Nodelinkrepository//Warehouse repository mode {private static imongocollection<nodelinks> _collectio 
 
 
    N Public ilist<nodelink> getlinks (int nodeId) {Nodelinks links = _collection. Find (x => x.id = = nodeId). Singleordefaultasync (). 
       
      result; 
 
      if (links = null) return to new nodelink[0]; Return links. 
    Links; Public Task savelinks (int nodeId, ienumerable<nodelink> links) {var nodelinks = new Nodelink 
      S (nodeId, links); 
 
      var updateOptions = new UpdateOptions {Isupsert = true}; Return _collection. 
    Replaceoneasync (x => x.id = = NodeId, nodelinks, updateOptions); } internal static void Init (String connectionString) {var client = new Mongoclient (connectionString) 
      ; Imongodatabase database = client. 
      Getdatabase ("Sqlwithmongo"); var collectionsettings = new Mongocollectionsettings {writeconcern = new Writeconcern (1)}; _collection = database. 
    Getcollection<nodelinks> ("links", collectionsettings); 
      Private class Nodelinks {public int Id {get; private set;} 
 
 
      Public list<nodelink> the Links {get; private set;} 
        Public nodelinks (int nodeId, ienumerable<nodelink> links) {Id = NodeId; 
        Links = new list<nodelink> (); 
      Links.addrange (links); 
 } 
    } 
  }
 public class Noderepository {private ReadOnly unitofwork; 
    Public noderepository (Unitofwork unitofwork) {_unitofwork = Unitofwork; 
    Public Node GetByID (int id) {return _unitofwork.get<node> (ID); Public ilist<node> GetAll () {return _unitofwork.query<node> (). 
    ToList (); 
    public void Save (Node mongonode) {_unitofwork.saveorupdate (Mongonode); } 
  } 
public class Mongonoderepository 
  { 
    private readonly unitofwork _unitofwork; 
 
 
    Public mongonoderepository (unitofwork unitofwork) 
    { 
      _unitofwork = unitofwork; 
    } 
 
 
    Public Mongonode GetByID (int id) 
    {return 
      _unitofwork.get<mongonode> (ID); 
    } 
 
 
    public void Save (Mongonode mongonode) 
    { 
      _unitofwork.saveorupdate (mongonode); 
    } 
 
 
    Public ilist<mongonode> GetAll () 
    {return 
      _unitofwork.query<mongonode> () 
        . ToList (); 
    } 
   

Model Layer Data:
The Node.cs,nodemap.cs class code is as follows:

 public class Node {public virtual int Id {get; protected set;} 
 
    Public virtual string Name {get; protected set;} 
    Protected virtual iset<node> linksinternal {get; set;} 
    Public virtual Ireadonlylist<node> The Links {get {return linksinternal.tolist ();} 
    } protected Node () {linksinternal = new hashset<node> (); 
    Public Node (string name): this () {name = name; 
      public virtual void Addlink (node node) {Linksinternal.add (node); Node. 
    Linksinternal.add (this); } 
  } 
public class nodemap:classmap<node>//fluentnhibernate.mapping.classlikemapbase<t> 
  { 
    public Nodemap () 
    { 
      Id (x => x.id, "NodeId"). Generatedby.hilo ("[dbo].[ Ids] "," Nexthigh "," Ten "," EntityName = ' Node ' "); 
      Map (x => x.name). Not.nullable (); 
 
      Hasmanytomany<node> (reveal.member<node> ("linksinternal")) 
        . AsSet () 
        . Table ("Node_node") 
        . ParentKeyColumn ("NodeId1") 
        . Childkeycolumn ("NodeId2"); 
    } 
   

The code for MongoNode.cs and MongoNodeMap.cs is as follows:

 public class Mongonode {public virtual int Id {get; protected set;} 
 
   Public virtual string Name {get; protected set;} 
   Protected virtual hashset<nodelink> linksinternal {get; set;} 
   Public virtual Ireadonlylist<nodelink> The Links {get {return linksinternal.tolist ();} 
   } protected Mongonode () {linksinternal = new hashset<nodelink> (); 
   Mongonode (string name): this () {name = name; public virtual void Addlink (Mongonode mongonode) {linksinternal.add (new Nodelink (Mongonode.id, Mongon Ode. 
     Name)); 
   MONGONODE.LINKSINTERNAL.ADD (New Nodelink (Id, Name)); } 
 } 
The class in the public class Mongonodemap:classmap<mongonode>//fluentnhibernate inherits 
  {public 
    mongonodemap () 
    { 
      Id (x => x.id, "Mongonodeid"). Generatedby.hilo ("[dbo].[ Ids] "," Nexthigh "," Ten "," EntityName = ' mongonode ' "); 
      Map (x => x.name). Not.nullable (); 
    } 
   

Class of Utils layer:
EventListener.cs content:

 internal class Eventlistener:ipostloadeventlistener//nhibernate.event inheritance {p ublic void Onpostload (postloadevent ev) {var networknode = ev. 
 
      Entity as Mongonode; 
 
      if (Networknode = null) return; 
      var repository = new Nodelinkrepository (); Ilist<nodelink> Linksfrommongo = Repository. 
 
      Getlinks (networknode.id); Hashset<nodelink> links = (hashset<nodelink>) networknode. GetType (). GetProperty ("Linksinternal", BindingFlags.NonPublic | bindingflags.instance). 
      GetValue (Networknode); Links. 
    Unionwith (Linksfrommongo); } 
  } 
class {public override void Postflush in internal class Interceptor:emptyinterceptor//nhibernate 
   (ICollection Entities) 
   { 
     ienumerable<mongonode> nodes = entities. Oftype<mongonode> (); 
 
     if (!nodes. Any ()) return 
       ; 
 
     var repository = new Nodelinkrepository (); 
     task[] Tasks = nodes. Select (x => repository. Savelinks (X.id, X.links)). ToArray (); 
     Task.waitall (tasks); 
   } 
  

UnitOfWork.cs Code:

public class Unitofwork:idisposable {private readonly isession _session; 
   Private ReadOnly ITransaction _transaction; 
   private bool _isalive = true; 
 
   private bool _iscommitted; 
     Public Unitofwork () {_session = Sessionfactory.opensession (); _transaction = _session. 
   BeginTransaction (isolationlevel.readcommitted); 
 
     public void Dispose () {if (!_isalive) return; 
 
     _isalive = false; 
       try {if (_iscommitted) {_transaction.commit (); }} finally {_transaction. 
       Dispose (); _session. 
     Dispose (); 
 
     } public void Commit () {if (!_isalive) return; 
   _iscommitted = true; } internal T get<t> (int id) {return _session. 
   Get<t> (ID); } internal void saveorupdate<t> (T entity) {_session. 
   Saveorupdate (entity); } Internal iqueryable<t> Query<t> () {return _session. 
   Query<t> (); 
 } 
 }

Database.sql Table statement:

CREATE DATABASE [Sqlwithmongo] Go the [Sqlwithmongo] go/****** table [dbo]. [Ids] ******/set ANSI_NULLS on Go Set QUOTED_IDENTIFIER in Go CREATE TABLE [dbo]. [Ids] 
  ([entityname] [nvarchar] (m) not NULL, [Nexthigh] [int] NOT NULL, CONSTRAINT [pk_ids] PRIMARY KEY CLUSTERED ( [EntityName] ASC) with (Pad_index = off, Statistics_norecompute = off, Ignore_dup_key = off, Allow_row_locks = on, Allow_page_locks = On to [PRIMARY] on [PRIMARY] go/****** table [dbo]. [Mongonode] ******/SET ansi_nulls on Go Set QUOTED_IDENTIFIER in Go CREATE TABLE [dbo]. [Mongonode]  
([Mongonodeid] [int] NOT NULL, [Name] [nvarchar] (m) not NULL, CONSTRAINT [Pk_mongonode] PRIMARY KEY CLUSTERED ([Mongonodeid] ASC)  With (Pad_index = off, Statistics_norecompute = off, Ignore_dup_key = off, Allow_row_locks = on, allow_page_locks = ON) on [PRIMARY]) On [PRIMARY] go/****** table [dbo]. [Node] ******/set ANSI_NULLS on Go Set QUOTED_IDENTIFIER in Go CREATE TABLE [dbo]. [NoDe] ([NodeId] [int] NOT NULL, [Name] [nvarchar] (m) not NULL, CONSTRAINT [Pk_networknode] PRIMARY KEY CLUSTERED ([NodeId] ASC)  With (Pad_index = off, Statistics_norecompute = off, Ignore_dup_key = off, Allow_row_locks = on, allow_page_locks = ON) on [PRIMARY]) On [PRIMARY] go/****** table [dbo]. [Node_node] ******/SET ansi_nulls on Go Set QUOTED_IDENTIFIER in Go CREATE TABLE [dbo]. [Node_node] ([NODEID1] [int] NOT NULL, [NODEID2] [int] is not null, CONSTRAINT [Pk_networknode_networknode] PRIMARY KEY clustere D ([NODEID1] ASC, [NODEID2] ASC) with (Pad_index = off, Statistics_norecompute = off, Ignore_dup_key = off, ALLO W_row_locks = ON, "allow_page_locks = on" on [PRIMARY]) on [PRIMARY] go ALTER TABLE [dbo]. [Node_node] With CHECK ADD CONSTRAINT [Fk_networknode_networknode_networknode] FOREIGN KEY ([NodeId1]) REFERENCES [dbo]. [Node] 
([NodeId]) Go ALTER TABLE [dbo]. [Node_node] CHECK CONSTRAINT [Fk_networknode_networknode_networknode] Go ALTERTABLE [dbo]. [Node_node] With CHECK ADD CONSTRAINT [fk_networknode_networknode_networknode1] FOREIGN KEY ([NodeId2]) REFERENCES [dbo]. [Node] 
([NodeId]) Go ALTER TABLE [dbo]. [Node_node] CHECK CONSTRAINT [fk_networknode_networknode_networknode1] Go INSERT dbo. Ids (EntityName, Nexthigh) VALUES (' Mongonode ', 0) INSERT dbo. 
 Ids (EntityName, Nexthigh) VALUES (' Node ', 0)

The result is as shown in figure:

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.