├── _config.yml ├── icon ├── NeoClient.png └── NeoClient_nuget.png ├── NeoClient.Tests ├── IntegrationTests.cs ├── Models │ └── User.cs ├── resources │ └── docker-compose.yml ├── NeoClient.Tests.csproj └── IntegrationTestBase.cs ├── NeoClient ├── Attributes │ ├── Direction.cs │ ├── NotMappedAttribute.cs │ └── RelationShipAttribute.cs ├── TransactionManager │ ├── IInternalTransaction.cs │ ├── ITransaction.cs │ └── Transaction.cs ├── Extensions │ ├── DateTimeExtensions.cs │ ├── DictionaryExtensions.cs │ ├── StatementResultExtensions.cs │ ├── CollectionExtensions.cs │ └── ObjectExtensions.cs ├── EntityBase.cs ├── Utilities │ └── StringFormatter.cs ├── NeoClient.csproj ├── Templates │ └── QueryTemplates.cs ├── INeoClient.cs └── NeoClient.cs ├── LICENSE ├── NeoClient.sln ├── .github └── workflows │ └── main.yml ├── .gitignore └── README.md /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-midnight -------------------------------------------------------------------------------- /icon/NeoClient.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OKTAYKIR/NeoClient/HEAD/icon/NeoClient.png -------------------------------------------------------------------------------- /icon/NeoClient_nuget.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OKTAYKIR/NeoClient/HEAD/icon/NeoClient_nuget.png -------------------------------------------------------------------------------- /NeoClient.Tests/IntegrationTests.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/OKTAYKIR/NeoClient/HEAD/NeoClient.Tests/IntegrationTests.cs -------------------------------------------------------------------------------- /NeoClient/Attributes/Direction.cs: -------------------------------------------------------------------------------- 1 | namespace NeoClient.Attributes 2 | { 3 | public enum DIRECTION 4 | { 5 | INCOMING, 6 | OUTGOING 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /NeoClient/Attributes/NotMappedAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NeoClient.Attributes 4 | { 5 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] 6 | public class NotMappedAttribute : Attribute 7 | { 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /NeoClient/TransactionManager/IInternalTransaction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NeoClient.TransactionManager 4 | { 5 | internal interface IInternalTransaction : IDisposable 6 | { 7 | Neo4j.Driver.V1.ITransaction CurrentTransaction { get; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /NeoClient/TransactionManager/ITransaction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NeoClient.TransactionManager 4 | { 5 | public interface ITransaction : IDisposable 6 | { 7 | void BeginTransaction(); 8 | void Commit(); 9 | void Rollback(); 10 | bool InTransaction { get; } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NeoClient.Tests/Models/User.cs: -------------------------------------------------------------------------------- 1 | namespace NeoClient.Tests.Models 2 | { 3 | public class User : EntityBase 4 | { 5 | public User() : base(label: "User") { } 6 | 7 | public string FirstName { get; set; } 8 | public string LastName { get; set; } 9 | public string Email { get; set; } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /NeoClient/Extensions/DateTimeExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace NeoClient.Extensions 4 | { 5 | public static class DateTimeExtensions 6 | { 7 | internal static double ToTimeStamp(this DateTime source) 8 | { 9 | return (source - new DateTime(1970, 1, 1)).TotalMilliseconds; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /NeoClient/EntityBase.cs: -------------------------------------------------------------------------------- 1 | namespace NeoClient 2 | { 3 | public abstract class EntityBase 4 | { 5 | public EntityBase(string label) 6 | { 7 | Label = label; 8 | } 9 | 10 | public string Label { get; internal set; } 11 | public string Uuid { get; internal set; } 12 | public bool IsDeleted { get; internal set; } 13 | } 14 | } -------------------------------------------------------------------------------- /NeoClient/Attributes/RelationShipAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace NeoClient.Attributes 6 | { 7 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] 8 | public class RelationshipAttribute : Attribute 9 | { 10 | public DIRECTION Direction { get; set; } = DIRECTION.INCOMING; 11 | public string Name { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /NeoClient.Tests/resources/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | networks: 4 | neo4j-network: 5 | driver: bridge 6 | 7 | services: 8 | neo4j: 9 | image: neo4j 10 | restart: unless-stopped 11 | ports: 12 | - 7474:7474 13 | - 6477:6477 14 | - 7687:7687 15 | environment: 16 | - NEO4J_AUTH=neo4j/changeme 17 | - NEO4J_dbms_connector_bolt_advertised__address='localhost:7687' 18 | - NEO4J_dbms_connector_bolt_tls__level=DISABLED 19 | networks: 20 | - neo4j-network 21 | -------------------------------------------------------------------------------- /NeoClient.Tests/NeoClient.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp3.1 5 | 6 | false 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /NeoClient/Utilities/StringFormatter.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | namespace NeoClient.Utilities 5 | { 6 | public class StringFormatter 7 | { 8 | public string Str { get; set; } 9 | 10 | public Dictionary Parameters { get; set; } 11 | 12 | public StringFormatter(string p_str) 13 | { 14 | Str = p_str; 15 | Parameters = new Dictionary(); 16 | } 17 | 18 | public void Add(string key, object val) 19 | { 20 | Parameters.Add(key, val); 21 | } 22 | 23 | public bool Remove(string key) 24 | { 25 | return Parameters.Remove(key); 26 | } 27 | 28 | public override string ToString() 29 | { 30 | return Parameters.Aggregate(Str, (current, parameter) => current.Replace(parameter.Key, parameter.Value.ToString())); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /NeoClient/Extensions/DictionaryExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | namespace NeoClient.Extensions 6 | { 7 | public static class DictionaryExtensions 8 | { 9 | public static void Map(this IReadOnlyDictionary dict, T obj) 10 | { 11 | var type = typeof(T); 12 | var properties = type.GetProperties().Where(p => p.CanRead && p.CanWrite && dict.ContainsKey(p.Name)); 13 | 14 | foreach (var property in properties) 15 | { 16 | var value = Convert.ChangeType(dict[property.Name], property.PropertyType); 17 | property.SetValue(obj, value); 18 | } 19 | } 20 | 21 | public static T Map(this IReadOnlyDictionary dict) where T : new() 22 | { 23 | var result = new T(); 24 | 25 | Map(dict, result); 26 | 27 | return result; 28 | } 29 | } 30 | } -------------------------------------------------------------------------------- /NeoClient.Tests/IntegrationTestBase.cs: -------------------------------------------------------------------------------- 1 | using Neo4j.Driver.V1; 2 | using System; 3 | 4 | namespace NeoClient.Tests 5 | { 6 | public abstract class IntegrationTestBase : IDisposable 7 | { 8 | #region Variables 9 | internal const string URL = "bolt://localhost:7687"; 10 | internal const string USER = "neo4j"; 11 | internal const string PASSWORD = "changeme"; 12 | internal static readonly Config CONFIG = Config.Builder 13 | .WithEncryptionLevel(EncryptionLevel.None) 14 | .ToConfig(); 15 | #endregion 16 | 17 | public virtual void Dispose(bool isDisposing) 18 | { 19 | if (!isDisposing) 20 | return; 21 | 22 | using (INeoClient client = new NeoClient(URL, USER, PASSWORD, CONFIG)) 23 | { 24 | client.Connect(); 25 | client.RunCustomQuery("MATCH (n) DETACH DELETE n"); 26 | } 27 | } 28 | 29 | public void Dispose() 30 | { 31 | Dispose(true); 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Oktay Kır , PhD 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /NeoClient/Extensions/StatementResultExtensions.cs: -------------------------------------------------------------------------------- 1 | using Neo4j.Driver.V1; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | 6 | namespace NeoClient.Extensions 7 | { 8 | public static class StatementResultExtensions 9 | { 10 | public static T Map(this IStatementResult statementResult) where T : new() 11 | { 12 | var recordValue = statementResult?.FirstOrDefault()?[0]; 13 | 14 | if (recordValue == null) 15 | return default; 16 | 17 | var properties = recordValue.As().Properties; 18 | 19 | return properties == null ? default : properties.Map(); 20 | } 21 | 22 | public static IList GetValues(this IStatementResult source) 23 | { 24 | if (source == null) 25 | return null; 26 | 27 | var entites = new Lazy>(); 28 | 29 | foreach (IRecord record in source) 30 | { 31 | var node = record.Values.As>(); 32 | 33 | entites.Value.Add(node); 34 | } 35 | 36 | return entites.Value; 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /NeoClient/NeoClient.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0;netstandard2.1;net472 5 | Oktay Kır 6 | true 7 | https://github.com/OKTAYKIR/NeoClient 8 | https://github.com/OKTAYKIR/NeoClient 9 | NeoClient_nuget.png 10 | 1.2 11 | neo4j ogm bolt cyper graphdb graphdatabase nosql 12 | Lightweight OGM for Neo4j which support transactions and BOLT protocol. 13 | 14 | 15 | 16 | false 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | True 28 | 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /NeoClient/Extensions/CollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Dynamic; 3 | using System.Text; 4 | 5 | namespace NeoClient.Extensions 6 | { 7 | public static class CollectionExtensions 8 | { 9 | internal static dynamic AsQueryClause(this Dictionary source) 10 | { 11 | dynamic properties = new ExpandoObject(); 12 | bool firstNode = true; 13 | StringBuilder clause = new StringBuilder(); 14 | var parameters = new Dictionary(); 15 | 16 | foreach (var item in source) 17 | { 18 | object value = item.Value; 19 | 20 | parameters[item.Key] = item.Value; 21 | 22 | if (value.GetType() == typeof(string)) 23 | { 24 | string sValue = value as string; 25 | sValue = sValue.Replace("\"", string.Empty); 26 | parameters[item.Key] = value as string; 27 | } 28 | else 29 | { 30 | parameters[item.Key] = value; 31 | } 32 | 33 | if (firstNode) 34 | firstNode = false; 35 | else 36 | clause.Append(","); 37 | 38 | clause.Append(string.Format("{0}:${0}", item.Key)); 39 | } 40 | 41 | properties.parameters = parameters; 42 | properties.clause = clause; 43 | 44 | return properties; 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /NeoClient.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.29926.136 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "NeoClient", "NeoClient\NeoClient.csproj", "{05D81BC9-DA31-494A-AC8F-1622F5DCE6B5}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NeoClient.Tests", "NeoClient.Tests\NeoClient.Tests.csproj", "{A01064FD-2D40-4206-8824-F71EC4A3D7C2}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {05D81BC9-DA31-494A-AC8F-1622F5DCE6B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {05D81BC9-DA31-494A-AC8F-1622F5DCE6B5}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {05D81BC9-DA31-494A-AC8F-1622F5DCE6B5}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {05D81BC9-DA31-494A-AC8F-1622F5DCE6B5}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {A01064FD-2D40-4206-8824-F71EC4A3D7C2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {A01064FD-2D40-4206-8824-F71EC4A3D7C2}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {A01064FD-2D40-4206-8824-F71EC4A3D7C2}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {A01064FD-2D40-4206-8824-F71EC4A3D7C2}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {20646619-2A8A-4BB6-96FA-C9B147AF4FB6} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /NeoClient/TransactionManager/Transaction.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using Neo4j.Driver.V1; 3 | 4 | namespace NeoClient.TransactionManager 5 | { 6 | public class Transaction : ITransaction, IInternalTransaction, IDisposable 7 | { 8 | public Transaction(IDriver driver) 9 | { 10 | _driver = driver; 11 | } 12 | 13 | public void Dispose() 14 | { 15 | _currentTransaction?.Dispose(); 16 | 17 | _currentTransaction = null; 18 | } 19 | 20 | #region Private variables 21 | private IDriver _driver; 22 | private Neo4j.Driver.V1.ITransaction _currentTransaction { get; set; } 23 | #endregion 24 | 25 | #region Public variables 26 | public bool InTransaction { get; set; } 27 | #endregion 28 | 29 | #region Public methods 30 | public void Commit() 31 | { 32 | _currentTransaction?.Success(); 33 | 34 | this.Dispose(); 35 | //_currentTransaction?.Dispose(); 36 | 37 | //_currentTransaction = null; 38 | 39 | //InTransaction = false; 40 | } 41 | 42 | public void Rollback() 43 | { 44 | _currentTransaction?.Failure(); 45 | 46 | this.Dispose(); 47 | 48 | //_currentTransaction?.Dispose(); 49 | 50 | //_currentTransaction = null; 51 | 52 | //InTransaction = false; 53 | } 54 | 55 | public void BeginTransaction() 56 | { 57 | _currentTransaction = _driver.Session().BeginTransaction(); 58 | 59 | InTransaction = true; 60 | } 61 | #endregion 62 | 63 | Neo4j.Driver.V1.ITransaction IInternalTransaction.CurrentTransaction { get => _currentTransaction; } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /NeoClient/Templates/QueryTemplates.cs: -------------------------------------------------------------------------------- 1 | namespace NeoClient.Templates 2 | { 3 | internal static class QueryTemplates 4 | { 5 | internal static string TEMPLATE_CREATE = @"@match CREATE(n:@node{@conditions}) @clause RETURN n"; 6 | internal static string TEMPLATE_MERGE = @"MERGE (n:@node{@conditions}) @on_create_clause @on_match_clause RETURN n"; 7 | internal static string TEMPLATE_GET_ALL = @"MATCH (n:@label{IsDeleted:false}) @where RETURN @result"; 8 | internal static string TEMPLATE_GET_BY_PROPERTY = @"MATCH (n:@label{@property:$value,IsDeleted:false})@relationship@relatedNode RETURN @result"; 9 | internal static string TEMPLATE_GET_BY_PROPERTIES = @"MATCH (n:@label{@clause,IsDeleted:false})@relationship@relatedNode RETURN @result"; 10 | internal static string TEMPLATE_DELETE = @"MATCH(n:@label{Uuid:""@Uuid"",IsDeleted:false}) SET n.updatedAt=@updatedAt,n.IsDeleted=true RETURN n"; 11 | internal static string TEMPLATE_UPDATE = @"MATCH(n:@label{Uuid:""@Uuid"",IsDeleted:false}) SET @clause @return"; 12 | 13 | internal static string TEMPLATE_CREATE_RELATIONSHIP = @"MATCH(from{Uuid:""@uuidFrom""}),(to{Uuid:""@uuidTo""}) CREATE (from)@fromPartDirection[r:@relationshipName@clause]@toPartDirection(to) RETURN r"; 14 | internal static string TEMPLATE_MERGE_RELATIONSHIP = @"MATCH(from{Uuid:""@uuidFrom""}),(to{Uuid:""@uuidTo""}) MERGE (from)@fromPartDirection[r:@relationshipName]@toPartDirection(to) RETURN r"; 15 | internal static string TEMPLATE_DROP_RELATIONSHIPBETWEENTWONODES = @"MATCH({Uuid:""@uuidIncoming""})@fromPartDirection[r:@relationshipName]@toPartDirection({Uuid:""@uuidOutgoing""}) DELETE r"; 16 | internal static string TEMPLATE_DROP = @"MATCH(n:@label{Uuid:""@Uuid""}) DETACH DELETE n"; 17 | internal static string TEMPLATE_DROP_BY_PROPERTIES = @"MATCH(n:@label{@clause}) DETACH DELETE n"; 18 | internal static string TEMPLATE_ADD_LABEL = @"MATCH (n{Uuid:""@Uuid""}) SET n:@label"; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /NeoClient/Extensions/ObjectExtensions.cs: -------------------------------------------------------------------------------- 1 | using NeoClient.Attributes; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Dynamic; 5 | using System.Linq; 6 | using System.Linq.Expressions; 7 | using System.Reflection; 8 | using System.Text; 9 | 10 | namespace NeoClient.Extensions 11 | { 12 | public static class ObjectExtensions 13 | { 14 | internal static dynamic AsUpdateClause(this object source, string prefix) 15 | { 16 | dynamic properties = new ExpandoObject(); 17 | bool firstNode = true; 18 | StringBuilder clause = new StringBuilder(); 19 | var parameters = new Dictionary(); 20 | 21 | foreach (PropertyInfo prop in source.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(x => !x.Name.Equals("createdAt"))) 22 | { 23 | if (prop.GetCustomAttribute(typeof(NotMappedAttribute), true) != null || 24 | prop.GetCustomAttribute(typeof(RelationshipAttribute), true) != null) 25 | continue; 26 | 27 | parameters[prop.Name] = prop.GetValue(source, null); 28 | 29 | if (firstNode) 30 | firstNode = false; 31 | else 32 | clause.Append(","); 33 | 34 | clause.Append(string.Format("{0}.{1}=${1}", prefix, prop.Name)); 35 | } 36 | 37 | properties.parameters = parameters; 38 | properties.clause = clause; 39 | 40 | return properties; 41 | } 42 | 43 | internal static IEnumerable GetRelationshipAttributes(this T obj, Expression> value) 44 | { 45 | MemberExpression memberExpression = value.Body as MemberExpression; 46 | 47 | return (IEnumerable)memberExpression.Member.GetCustomAttributes(typeof(RelationshipAttribute), true); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | # This is a basic workflow to help you get started with Actions 2 | 3 | name: CI 4 | 5 | # Controls when the action will run. Triggers the workflow on push or pull request 6 | # events but only for the master branch 7 | on: 8 | push: 9 | branches: [ master ] 10 | pull_request: 11 | branches: [ master ] 12 | 13 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 14 | jobs: 15 | # This workflow contains a single job called "build" 16 | build: 17 | # The type of runner that the job will run on 18 | runs-on: ubuntu-latest 19 | 20 | # Steps represent a sequence of tasks that will be executed as part of the job 21 | steps: 22 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 23 | - uses: actions/checkout@v2 24 | 25 | - name: Setup .NET Core 26 | uses: actions/setup-dotnet@v1 27 | with: 28 | dotnet-version: 3.1.101 29 | 30 | - name: NeoClient Build -f netstandard2.0 31 | run: dotnet build NeoClient/NeoClient.csproj --configuration Release -f netstandard2.0 32 | 33 | - name: NeoClient Build -f netstandard2.1 34 | run: dotnet build NeoClient/NeoClient.csproj --configuration Release -f netstandard2.1 35 | 36 | - name: NeoClient.Tests Build -f netcoreapp3.1 37 | run: dotnet build NeoClient.Tests/NeoClient.Tests.csproj --configuration Release -f netcoreapp3.1 38 | 39 | - name: Build the stack 40 | run: docker-compose -f NeoClient.Tests/resources/docker-compose.yml up -d 41 | 42 | - name: Sleep 43 | uses: jakejarvis/wait-action@master 44 | with: 45 | time: '5s' 46 | 47 | - name: Check running containers 48 | run: docker ps -a 49 | 50 | - name: Check logs 51 | run: docker-compose -f NeoClient.Tests/resources/docker-compose.yml logs 52 | 53 | - name: Tests 54 | run: dotnet test NeoClient.Tests/NeoClient.Tests.csproj --configuration Release 55 | -------------------------------------------------------------------------------- /NeoClient/INeoClient.cs: -------------------------------------------------------------------------------- 1 | using Neo4j.Driver.V1; 2 | using NeoClient.Attributes; 3 | using System; 4 | using System.Collections.Generic; 5 | using ITransaction = NeoClient.TransactionManager.ITransaction; 6 | 7 | namespace NeoClient 8 | { 9 | public interface INeoClient : IDisposable 10 | { 11 | IList GetByProperty( 12 | string propertyName, 13 | object propertValue) where T : EntityBase, new(); 14 | IList GetByProperties(Dictionary entity) where T : EntityBase, new(); 15 | T Add(T entity) where T : EntityBase, new(); 16 | T Update( 17 | T entity, 18 | string id, 19 | bool fetchResult = false) where T : EntityBase, new(); 20 | T Delete(string uuid) where T : EntityBase, new(); 21 | T GetByUuidWithRelatedNodes(string uuid) where T : EntityBase, new(); 22 | IList GetAll(string where = default) where T : EntityBase, new(); 23 | bool CreateRelationship( 24 | string uuidFrom, 25 | string uuidTo, 26 | RelationshipAttribute relationshipAttribute, 27 | Dictionary props = null); 28 | T Merge( 29 | T entityOnCreate, 30 | T entityOnUpdate, 31 | string where) where T : EntityBase, new(); 32 | bool MergeRelationship( 33 | string uuidFrom, 34 | string uuidTo, 35 | RelationshipAttribute relationshipAttribute); 36 | bool Drop(string uuid) where T : EntityBase, new(); 37 | bool DropRelationshipBetweenTwoNodes( 38 | string uuidIncoming, 39 | string uuidOutgoing, 40 | RelationshipAttribute relationshipAttribute); 41 | IList RunCustomQuery( 42 | string query, 43 | Dictionary parameters) where T : class, new(); 44 | IStatementResult RunCustomQuery( 45 | string query, 46 | Dictionary parameters = null); 47 | //TODO: will be removed after isDeleted refactor 48 | int DropByProperties(Dictionary props) where T : EntityBase, new(); 49 | bool AddLabel(string uuid, string newLabelName); 50 | void Connect(); 51 | ITransaction BeginTransaction(); 52 | bool Ping(); 53 | } 54 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | NeoClient logo 3 | 4 | # NeoClient 5 | ![Hits](https://hitcounter.pythonanywhere.com/count/tag.svg?url=https://github.com/OKTAYKIR/NeoClient) 6 | ![GitHub issues](https://img.shields.io/github/issues/OKTAYKIR/NeoClient) 7 | ![Build Status](https://github.com/OKTAYKIR/NeoClient/workflows/CI/badge.svg?branch=master) 8 | [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](#contributing) 9 | [![nuget](https://img.shields.io/nuget/v/NeoClient)](https://www.nuget.org/packages/NeoClient/) 10 | 11 | A Lightweight and simple object graph mapper (OGM) for [Neo4j](https://neo4j.com) which support transactions and BOLT protocol. 12 | 13 | ## :package: Installation 14 | NeoClient is available on [NuGet](https://www.nuget.org/packages/NeoClient/). 15 | 16 | ```sh 17 | dotnet add package NeoClient 18 | ``` 19 | ## Examples 20 | * **[NeoClient](https://github.com/OKTAYKIR/NeoClientDemo):** Neo4j Movies Example Application - Asp.net WebApi Version 21 | 22 | ## 🚀 Usage 23 | 24 | ### Creating Database Connection 25 | Optional you can pass authentication credential via the constructor. 26 | ```csharp 27 | INeoClient client = new NeoClient( 28 | uri: "bolt://localhost:7687", 29 | userName: "user", //optional 30 | password: "password", //optional 31 | config: Config.Builder //optional 32 | .WithMaxConnectionLifetime(TimeSpan.FromMinutes(30)) 33 | .WithMaxConnectionPoolSize(100) 34 | .WithConnectionAcquisitionTimeout(TimeSpan.FromMinutes(2)) 35 | .WithEncryptionLevel(EncryptionLevel.None) 36 | .ToConfig() 37 | strip_hyphens: true //optional, default is false 38 | ); 39 | client.Connect(); 40 | ``` 41 | 42 | For example, if you were using any IoC container, you could register the client like so: 43 | ```csharp 44 | container.Register((c, p) => 45 | { 46 | INeoClient client = new NeoClient( 47 | uri: "bolt://localhost:7687", 48 | ... 49 | ); 50 | client.Connect(); 51 | return client; 52 | }); 53 | ``` 54 | ### User Node Model 55 | ```csharp 56 | public class User : EntityBase 57 | { 58 | public User() : base(label: "User") { } 59 | 60 | public string FirstName { get; set; } 61 | public string LastName { get; set; } 62 | public string Email { get; set; } 63 | } 64 | ``` 65 | 66 | ### Creating a Node 67 | ```csharp 68 | User entity = client.Add(new User { Email = "kir.oktay@gmail.com", FirstName = "Oktay", LastName = "Kir" }); 69 | ``` 70 | 71 | ### Adding a Label to a Node 72 | ```csharp 73 | bool result = client.AddLabel( 74 | uuid: "01a68df3-cc35-4eb0-a199-0d924da86eab", 75 | labelName: @"LabelName" 76 | ); 77 | ``` 78 | 79 | ### Retrieving a Node by Id 80 | ```csharp 81 | User node = client.GetByUuidWithRelatedNodes("01a68df3-cc35-4eb0-a199-0d924da86eab"); 82 | ``` 83 | 84 | ### Retrieving All Nodes 85 | ```csharp 86 | IList nodes = client.GetAll(); 87 | ``` 88 | 89 | ### Retrieving Nodes by Single Property 90 | ```csharp 91 | IList nodes = client.GetByProperty("Email", "kir.oktay@gmail.com"); 92 | ``` 93 | 94 | ### Retrieving Nodes by Multiple Properties 95 | ```csharp 96 | var properties = new Dictionary(){ 97 | { nameof(User.Name), "keanu"}, 98 | }; 99 | 100 | IList nodes = client.GetByProperties(properties); 101 | ``` 102 | 103 | ### Updating a Node 104 | ```csharp 105 | User updatedNode = client.Update( 106 | entity: node, 107 | uuid: "01a68df3-cc35-4eb0-a199-0d924da86eab", 108 | fetchResult: true //optional, default is false 109 | ); 110 | ``` 111 | 112 | ### Deleting a Node (Soft Delete) 113 | ```csharp 114 | User node = client.Delete("01a68df3-cc35-4eb0-a199-0d924da86eab"); 115 | ``` 116 | 117 | ### Dropping a Node by Id 118 | ```csharp 119 | bool result = client.Drop("01a68df3-cc35-4eb0-a199-0d924da86eab"); 120 | ``` 121 | 122 | ### Drop Nodes by Properties 123 | ```csharp 124 | int nodesDeleted = client.DropByProperties( 125 | props: new Dictionary(){ 126 | { nameof(User.Name), "keanu"}, 127 | } 128 | ); 129 | ``` 130 | 131 | ### Create a Relationship Between Certain Two Nodes 132 | ```csharp 133 | bool isCreated = client.CreateRelationship( 134 | uuidFrom: "2ac55031-3089-453a-a858-e1a9a8b68a16", 135 | uuidTo: "ac43523a-a15e-4d25-876e-e2a2cc4de125", 136 | relationshipAttribute: new RelationshipAttribute{ 137 | Direction = DIRECTION.INCOMING, 138 | Name = "FAMILY" 139 | }, 140 | props: new Dictionary(){ //optional 141 | {"CreatedAt", DateTime.UtcNow}, 142 | {"Kinship_Level", 1}, 143 | {"Name", "FakeName"} 144 | } 145 | ); 146 | ``` 147 | 148 | ### Dropping a Relationship Between Certain Two Nodes 149 | ```csharp 150 | bool result = client.DropRelationshipBetweenTwoNodes( 151 | uuidFrom: "2ac55031-3089-453a-a858-e1a9a8b68a16", 152 | uuidTo: "ac43523a-a15e-4d25-876e-e2a2cc4de125", 153 | relationshipAttribute: node.GetRelationshipAttributes(ep => ep.roles).FirstOrDefault() 154 | ); 155 | ``` 156 | 157 | ### Merge Nodes 158 | Creating a node with its properties on creation time. If the nodes had already been found, different multiple properties would have been set. 159 | ```csharp 160 | User node = client.Merge( 161 | entityOnCreate: new User(){ name = "keanu"; createdAt = DateTime.UtcNow.ToTimeStamp(); }, 162 | entityOnUpdate: new User(){ name = "keanu"; updatedAt = DateTime.UtcNow.ToTimeStamp(); }, 163 | where: "name:\"keanu\"" 164 | ); 165 | ``` 166 | 167 | ### Merge Relationships 168 | ```csharp 169 | bool result = client.MergeRelationship( 170 | uuidFrom: "2ac55031-3089-453a-a858-e1a9a8b68a16", 171 | uuidTo: "ac43523a-a15e-4d25-876e-e2a2cc4de125", 172 | relationshipAttribute: node.GetRelationshipAttributes(ep => ep.roles).FirstOrDefault() 173 | ); 174 | ``` 175 | 176 | ### Running Custom Cypher Query 177 | #### Example 1: 178 | ```csharp 179 | string cypherCreateQuery = @"CREATE (Neo:Crew {name:'Neo'}), 180 | (Morpheus:Crew {name: 'Morpheus'}), 181 | (Trinity:Crew {name: 'Trinity'}), 182 | (Cypher:Crew:Matrix {name: 'Cypher'}), 183 | (Smith:Matrix {name: 'Agent Smith'}), 184 | (Architect:Matrix {name:'The Architect'}), 185 | (Neo)-[:KNOWS]->(Morpheus), 186 | (Neo)-[:LOVES]->(Trinity), 187 | (Morpheus)-[:KNOWS]->(Trinity), 188 | (Morpheus)-[:KNOWS]->(Cypher), 189 | (Cypher)-[:KNOWS]->(Smith), 190 | (Smith)-[:CODED_BY]->(Architect)"; 191 | 192 | IStatementResult result = client.RunCustomQuery(query: cypherQuery); 193 | 194 | string cypherQuery = @"MATCH (n:Crew)-[r:KNOWS*]-(m) WHERE n.name='Neo' RETURN n AS Neo,r,m"; 195 | 196 | IStatementResult queryResult = client.RunCustomQuery(query: cypherQuery); 197 | IList result = queryResult.GetValues(); 198 | ``` 199 | #### Example 2: 200 | ```csharp 201 | string cypherQuery = @"MATCH (n:User) RETURN n"; 202 | 203 | IList result = client.RunCustomQuery(query: cypherQuery); 204 | ``` 205 | ## Integration Tests 206 | NeoClient has several tests that verify that its ability to use the system it integrates with correctly. 207 | 208 | There's a [docker-compose](NeoClient.Tests/resources/docker-compose.yml) file and you can use the following command to launch Neo4j container for running the integration tests. 209 | ``` 210 | $ docker-compose up -d 211 | ``` 212 | 213 | ## Transactions 214 | 215 | ## To Do 216 | - [x] Nuget package 217 | - [x] Integration Tests 218 | - [x] Creating example projects 219 | - [ ] Supporting more functionalities 220 | 221 | ## 🤝 Contributing 222 | 1. Fork it ( https://github.com/OKTAYKIR/NeoClient/fork ) 223 | 2. Create your feature branch (`git checkout -b my-new-feature`) 224 | 3. Commit your changes (`git commit -am 'Add some feature'`) 225 | 4. Push to the branch (`git push origin my-new-feature`) 226 | 5. Create a new Pull Request 227 | 228 | ## ✨ Contributors 229 | ![GitHub Contributors Image](https://contrib.rocks/image?repo=OKTAYKIR/NeoClient) 230 | 231 | ## Show your support 232 | Please ⭐️ this repository if this project helped you! 233 | 234 | ## 📝 License 235 | [MIT license](http://www.opensource.org/licenses/Mit) 236 | -------------------------------------------------------------------------------- /NeoClient/NeoClient.cs: -------------------------------------------------------------------------------- 1 | using AutoMapper; 2 | using Neo4j.Driver.V1; 3 | using NeoClient.Attributes; 4 | using NeoClient.Extensions; 5 | using NeoClient.Templates; 6 | using NeoClient.TransactionManager; 7 | using NeoClient.Utilities; 8 | using System; 9 | using System.Collections; 10 | using System.Collections.Generic; 11 | using System.Linq; 12 | using System.Reflection; 13 | using System.Text; 14 | 15 | namespace NeoClient 16 | { 17 | public class NeoClient : INeoClient 18 | { 19 | #region Private variables 20 | public static readonly string TAG = "n"; 21 | private static readonly string BIND_MARKER = "|"; 22 | 23 | private readonly string URI; 24 | private readonly string UserName; 25 | private readonly string Password; 26 | private readonly bool StripHyphens; 27 | private IDriver Driver; 28 | private TransactionManager.ITransaction Transaction = null; 29 | 30 | //#if NET45 31 | //#else 32 | private readonly Config Config = null; 33 | //#endif 34 | #endregion 35 | 36 | #region Public variables 37 | public bool IsConnected => Driver != null; 38 | #endregion 39 | 40 | public NeoClient( 41 | string uri, 42 | string userName = null, 43 | string password = null, 44 | //#if NET45 45 | //#else 46 | Config config = null, 47 | //#endif 48 | bool strip_hyphens = false) 49 | { 50 | this.URI = uri; 51 | this.UserName = userName; 52 | this.Password = password; 53 | this.StripHyphens = strip_hyphens; 54 | this.Config = config; 55 | 56 | Mapper.Initialize(mapper => { }); 57 | } 58 | 59 | protected virtual void Dispose(bool disposing) 60 | { 61 | if (!disposing) 62 | return; 63 | 64 | Transaction?.Dispose(); 65 | } 66 | 67 | public void Dispose() 68 | { 69 | Dispose(true); 70 | 71 | GC.SuppressFinalize(this); 72 | } 73 | 74 | public void Connect() 75 | { 76 | if (IsConnected) 77 | return; 78 | 79 | Driver = GraphDatabase.Driver( 80 | URI, 81 | (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password)) ? null : AuthTokens.Basic(UserName, Password), 82 | this.Config); 83 | } 84 | 85 | public TransactionManager.ITransaction BeginTransaction() 86 | { 87 | if (Driver == null) 88 | return null; 89 | 90 | Transaction = new Transaction(Driver); 91 | 92 | Transaction.BeginTransaction(); 93 | 94 | return Transaction; 95 | } 96 | 97 | private IStatementResult ExecuteQuery( 98 | string query, 99 | object parameters = null) 100 | { 101 | if (string.IsNullOrWhiteSpace(query)) 102 | throw new ArgumentNullException("query"); 103 | 104 | if (Transaction == null) 105 | { 106 | using (var session = Driver.Session()) 107 | { 108 | return parameters == null ? session.Run(query) : 109 | session.Run(query, parameters); 110 | } 111 | } 112 | 113 | var currentTransaction = ((IInternalTransaction)Transaction).CurrentTransaction; 114 | 115 | if (currentTransaction == null) 116 | throw new NullReferenceException("Transaction"); 117 | 118 | return parameters == null ? currentTransaction.Run(query.ToString()) : 119 | currentTransaction.Run(query.ToString(), parameters); 120 | } 121 | 122 | private IStatementResult ExecuteQuery( 123 | string query, 124 | IDictionary parameters) 125 | { 126 | if (string.IsNullOrWhiteSpace(query)) 127 | throw new ArgumentNullException("query"); 128 | 129 | if (Transaction == null) 130 | { 131 | using (var session = Driver.Session()) 132 | { 133 | return parameters == null ? session.Run(query) : 134 | session.Run(query, parameters); 135 | } 136 | } 137 | 138 | var currentTransaction = ((IInternalTransaction)Transaction).CurrentTransaction; 139 | 140 | if (currentTransaction == null) 141 | throw new NullReferenceException("Transaction"); 142 | 143 | return parameters == null ? currentTransaction.Run(query.ToString()) : 144 | currentTransaction.Run(query.ToString(), parameters); 145 | } 146 | 147 | private IDictionary FetchRelatedNode(string uuid) 148 | where T : EntityBase, new() 149 | { 150 | if (string.IsNullOrWhiteSpace(uuid)) 151 | throw new ArgumentNullException("uuid"); 152 | 153 | var query = new StringFormatter(QueryTemplates.TEMPLATE_GET_BY_PROPERTIES); 154 | 155 | query.Add("@label", new T().Label); 156 | query.Add("@clause", "Uuid:$Uuid"); 157 | query.Add("@result", TAG); 158 | query.Add("@relatedNode", string.Empty); 159 | query.Add("@relationship", string.Empty); 160 | 161 | var nodes = new Lazy>(); 162 | 163 | foreach (PropertyInfo prop in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) 164 | { 165 | if (prop.GetCustomAttribute(typeof(NotMappedAttribute), true) != null) 166 | continue; 167 | 168 | RelationshipAttribute relationshipAttribute = (RelationshipAttribute)prop.GetCustomAttributes(typeof(RelationshipAttribute), true).FirstOrDefault(); 169 | 170 | if (relationshipAttribute != null) 171 | { 172 | string labelName; 173 | if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnumerable))) 174 | { 175 | labelName = (Activator.CreateInstance(prop.PropertyType.GetGenericArguments()[0], null) as EntityBase).Label; 176 | } 177 | else 178 | { 179 | labelName = (Activator.CreateInstance(prop.PropertyType, null) as EntityBase).Label; 180 | } 181 | 182 | string parameterRelatedNode = string.Format(@"(rNode:{0}{{IsDeleted:false}})", labelName); 183 | 184 | string parameterRelationship = string.Format( 185 | @"{0}[r:{1}]{2}", 186 | relationshipAttribute.Direction == DIRECTION.INCOMING ? "<-" : "-", 187 | relationshipAttribute.Name, 188 | relationshipAttribute.Direction == DIRECTION.INCOMING ? "-" : "->"); 189 | 190 | query.Remove("@result"); 191 | query.Remove("@relatedNode"); 192 | query.Remove("@relationship"); 193 | 194 | query.Add("@relatedNode", parameterRelatedNode); 195 | query.Add("@relationship", parameterRelationship); 196 | query.Add("@result", "rNode"); 197 | 198 | IStatementResult resultRelatedNode = ExecuteQuery(query.ToString(), new { Uuid = uuid }); 199 | 200 | if (prop.PropertyType.GetInterfaces().Contains(typeof(IEnumerable))) 201 | { 202 | var relatedNodes = new Lazy>>(); 203 | 204 | foreach (IRecord record in resultRelatedNode) 205 | { 206 | IReadOnlyDictionary node = record[0].As().Properties; 207 | 208 | relatedNodes.Value.Add(node); 209 | } 210 | 211 | if (relatedNodes.IsValueCreated) 212 | { 213 | nodes.Value.Add(prop.Name, relatedNodes.Value); 214 | } 215 | } 216 | else 217 | { 218 | IReadOnlyDictionary relatedNode = resultRelatedNode.FirstOrDefault()?[0].As().Properties; 219 | 220 | if (relatedNode != null) 221 | { 222 | nodes.Value.Add(prop.Name, relatedNode); 223 | } 224 | } 225 | } 226 | } 227 | 228 | return nodes.Value; 229 | } 230 | 231 | public bool CreateRelationship( 232 | string uuidFrom, 233 | string uuidTo, 234 | RelationshipAttribute relationshipAttribute, 235 | Dictionary props = null) 236 | { 237 | if (string.IsNullOrWhiteSpace(uuidFrom)) 238 | throw new ArgumentNullException("uuidFrom"); 239 | 240 | if (string.IsNullOrWhiteSpace(uuidTo)) 241 | throw new ArgumentNullException("uuidTo"); 242 | 243 | if (relationshipAttribute == null) 244 | throw new ArgumentNullException("relationshipAttribute"); 245 | 246 | var query = new StringFormatter(QueryTemplates.TEMPLATE_CREATE_RELATIONSHIP); 247 | query.Add("@uuidFrom", uuidFrom); 248 | query.Add("@uuidTo", uuidTo); 249 | query.Add("@fromPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "<-" : "-"); 250 | query.Add("@toPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "-" : "->"); 251 | query.Add("@relationshipName", relationshipAttribute.Name); 252 | 253 | IStatementResult result; 254 | 255 | if (props != null) 256 | { 257 | dynamic properties = props.AsQueryClause(); 258 | dynamic clause = properties.clause; 259 | 260 | IDictionary parameters = properties.parameters; 261 | query.Add("@clause", $"{{{clause}}}"); 262 | result = ExecuteQuery(query.ToString(), parameters); 263 | } 264 | else 265 | { 266 | query.Add("@clause", string.Empty); 267 | result = ExecuteQuery(query.ToString()); 268 | } 269 | 270 | return result.Summary.Counters.RelationshipsCreated > 0; 271 | } 272 | 273 | public bool DropRelationshipBetweenTwoNodes( 274 | string uuidIncoming, 275 | string uuidOutgoing, 276 | RelationshipAttribute relationshipAttribute) 277 | { 278 | if (string.IsNullOrWhiteSpace(uuidIncoming)) 279 | throw new ArgumentNullException("uuidIncoming"); 280 | 281 | if (string.IsNullOrWhiteSpace(uuidOutgoing)) 282 | throw new ArgumentNullException("uuidOutgoing"); 283 | 284 | if (relationshipAttribute == null) 285 | throw new ArgumentNullException("relationshipAttribute"); 286 | 287 | var query = new StringFormatter(QueryTemplates.TEMPLATE_DROP_RELATIONSHIPBETWEENTWONODES); 288 | query.Add("@uuidIncoming", uuidIncoming); 289 | query.Add("@uuidOutgoing", uuidOutgoing); 290 | query.Add("@fromPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "<-" : "-"); 291 | query.Add("@toPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "-" : "->"); 292 | query.Add("@relationshipName", relationshipAttribute.Name); 293 | 294 | IStatementResult result = ExecuteQuery(query.ToString()); 295 | 296 | return result.Summary.Counters.RelationshipsDeleted > 0; 297 | } 298 | 299 | public bool MergeRelationship( 300 | string uuidFrom, 301 | string uuidTo, 302 | RelationshipAttribute relationshipAttribute) 303 | { 304 | if (string.IsNullOrWhiteSpace(uuidFrom)) 305 | throw new ArgumentNullException("uuidFrom"); 306 | 307 | if (string.IsNullOrWhiteSpace(uuidTo)) 308 | throw new ArgumentNullException("uuidTo"); 309 | 310 | if (relationshipAttribute == null) 311 | throw new ArgumentNullException("relationshipAttribute"); 312 | 313 | var query = new StringFormatter(QueryTemplates.TEMPLATE_MERGE_RELATIONSHIP); 314 | query.Add("@uuidFrom", uuidFrom); 315 | query.Add("@uuidTo", uuidTo); 316 | query.Add("@fromPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "<-" : "-"); 317 | query.Add("@toPartDirection", relationshipAttribute.Direction == DIRECTION.INCOMING ? "-" : "->"); 318 | query.Add("@relationshipName", relationshipAttribute.Name); 319 | 320 | IStatementResult result = ExecuteQuery(query.ToString()); 321 | 322 | return result.Any(); 323 | } 324 | 325 | public T Add(T entity) where T : EntityBase, new() 326 | { 327 | if (entity == null) 328 | throw new ArgumentNullException("entity"); 329 | 330 | StringFormatter match = null; 331 | string clause = null; 332 | bool firstNode = true; 333 | bool hasRelationship = false; 334 | 335 | var parameters = new Lazy>(); 336 | 337 | var conditions = new Lazy(); 338 | 339 | foreach (PropertyInfo prop in entity.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) 340 | { 341 | if (prop.GetCustomAttribute(typeof(NotMappedAttribute), true) != null || 342 | prop.GetCustomAttribute(typeof(RelationshipAttribute), true) != null) 343 | continue; 344 | 345 | if (prop.Name.Equals("Uuid", StringComparison.CurrentCultureIgnoreCase)) 346 | continue; 347 | 348 | parameters.Value[prop.Name] = prop.GetValue(entity, null); 349 | 350 | if (firstNode) 351 | firstNode = false; 352 | else 353 | conditions.Value.Append(","); 354 | 355 | conditions.Value.Append(string.Format("{0}:${0}", prop.Name)); 356 | } 357 | 358 | string uuid = StripHyphens ? Guid.NewGuid().ToString("N") : Guid.NewGuid().ToString(); 359 | 360 | parameters.Value["Uuid"] = uuid; 361 | conditions.Value.Append(firstNode ? "Uuid:$Uuid" : ",Uuid:$Uuid"); 362 | 363 | var query = new StringFormatter(QueryTemplates.TEMPLATE_CREATE); 364 | query.Add("@match", hasRelationship ? match.ToString() : string.Empty); 365 | query.Add("@node", entity.Label); 366 | query.Add("@conditions", conditions.Value.ToString()); 367 | query.Add("@clause", hasRelationship ? clause : string.Empty); 368 | 369 | IStatementResult result = ExecuteQuery(query.ToString(), parameters.Value); 370 | 371 | if(result.Summary.Counters.NodesCreated == 0) 372 | throw new Exception("Node creation error!"); 373 | 374 | return result.Map(); 375 | } 376 | 377 | public T Merge( 378 | T entityOnCreate, 379 | T entityOnUpdate, 380 | string where) where T : EntityBase, new() 381 | { 382 | if (entityOnCreate == null) 383 | throw new ArgumentNullException("entityOnCreate"); 384 | 385 | if (entityOnUpdate == null) 386 | throw new ArgumentNullException("entityOnUpdate"); 387 | 388 | bool firstNode = true; 389 | 390 | var setCaluseOnCreate = new Lazy(); 391 | var setCaluseOnUpdate = new Lazy(); 392 | 393 | var formattedSetClauseOnCreate = new StringFormatter(""); 394 | var formattedSetClauseOnUpdate = new StringFormatter(""); 395 | 396 | foreach (PropertyInfo prop in entityOnCreate.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) 397 | { 398 | if (prop.GetCustomAttribute(typeof(NotMappedAttribute), true) != null || 399 | prop.GetCustomAttribute(typeof(RelationshipAttribute), true) != null) 400 | continue; 401 | 402 | if (prop.Name.Equals("Uuid", StringComparison.CurrentCultureIgnoreCase)) 403 | { 404 | continue; 405 | } 406 | 407 | object value = prop.GetValue(entityOnCreate, null); 408 | 409 | string prefixAndPostfix = (value is string) ? "\"" : string.Empty; 410 | 411 | formattedSetClauseOnCreate.Add(BIND_MARKER + prop.Name + BIND_MARKER, prefixAndPostfix + (value ?? "null") + prefixAndPostfix); 412 | 413 | if (firstNode) 414 | { 415 | firstNode = false; 416 | } 417 | else 418 | { 419 | setCaluseOnCreate.Value.Append(","); 420 | } 421 | 422 | setCaluseOnCreate.Value.Append(string.Format("n.{0}={1}{0}{1}", prop.Name, BIND_MARKER)); 423 | } 424 | 425 | firstNode = true; 426 | foreach (PropertyInfo prop in entityOnUpdate.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)) 427 | { 428 | if (prop.GetCustomAttribute(typeof(NotMappedAttribute), true) != null || 429 | prop.GetCustomAttribute(typeof(RelationshipAttribute), true) != null) 430 | continue; 431 | 432 | if (prop.Name.Equals("Uuid", StringComparison.CurrentCultureIgnoreCase)) 433 | { 434 | continue; 435 | } 436 | 437 | object value = prop.GetValue(entityOnUpdate, null); 438 | 439 | string prefixAndPostfix = (value is string) ? "\"" : string.Empty; 440 | 441 | formattedSetClauseOnUpdate.Add(BIND_MARKER + prop.Name + BIND_MARKER, prefixAndPostfix + (value ?? "null") + prefixAndPostfix); 442 | 443 | if (firstNode) 444 | { 445 | firstNode = false; 446 | } 447 | else 448 | { 449 | setCaluseOnUpdate.Value.Append(","); 450 | } 451 | 452 | setCaluseOnUpdate.Value.Append(string.Format("n.{0}={1}{0}{1}", prop.Name, BIND_MARKER)); 453 | } 454 | 455 | string uuid = StripHyphens ? Guid.NewGuid().ToString("N") : Guid.NewGuid().ToString(); 456 | 457 | formattedSetClauseOnCreate.Add(string.Format("{0}Uuid{0}", BIND_MARKER), "\"" + uuid + "\""); 458 | 459 | setCaluseOnCreate.Value.Append(firstNode ? string.Format("n.Uuid={0}Uuid{0}", BIND_MARKER) : string.Format(",n.Uuid={0}Uuid{0}", BIND_MARKER)); 460 | 461 | formattedSetClauseOnCreate.Str = setCaluseOnCreate.Value.ToString(); 462 | formattedSetClauseOnUpdate.Str = setCaluseOnUpdate.Value.ToString(); 463 | 464 | var query = new StringFormatter(QueryTemplates.TEMPLATE_MERGE); 465 | query.Add("@node", entityOnCreate.Label); 466 | query.Add("@on_create_clause", string.Format("ON CREATE SET {0}", formattedSetClauseOnCreate.ToString())); 467 | query.Add("@on_match_clause", string.Format("ON MATCH SET {0}", formattedSetClauseOnUpdate.ToString())); 468 | query.Add("@conditions", where); 469 | 470 | IStatementResult statementResult = ExecuteQuery(query.ToString()); 471 | 472 | return statementResult.Map(); 473 | } 474 | 475 | public T Update( 476 | T entity, 477 | string uuid, 478 | bool fetchResult = false) where T : EntityBase, new() 479 | { 480 | if (entity == null) 481 | throw new ArgumentNullException("entity"); 482 | 483 | if (string.IsNullOrWhiteSpace(uuid)) 484 | throw new ArgumentNullException("uuid"); 485 | 486 | //entity.uuid = uuid; 487 | 488 | dynamic properties = entity.AsUpdateClause(TAG); 489 | dynamic clause = properties.clause; 490 | IDictionary parameters = properties.parameters; 491 | 492 | var query = new StringFormatter(QueryTemplates.TEMPLATE_UPDATE); 493 | query.Add("@label", entity.Label); 494 | query.Add("@Uuid", uuid); 495 | query.Add("@clause", clause); 496 | query.Add("@return", fetchResult ? string.Format("RETURN {0}", TAG) : string.Empty); 497 | 498 | IStatementResult result = ExecuteQuery(query.ToString(), parameters); 499 | 500 | return result.Map(); 501 | } 502 | 503 | public T Delete(string uuid) where T : EntityBase, new() 504 | { 505 | if (string.IsNullOrWhiteSpace(uuid)) 506 | throw new ArgumentNullException("uuid"); 507 | 508 | T model = new T(); 509 | 510 | var query = new StringFormatter(QueryTemplates.TEMPLATE_DELETE); 511 | query.Add("@label", model.Label); 512 | query.Add("@Uuid", uuid); 513 | query.Add("@updatedAt", DateTime.UtcNow.ToTimeStamp()); 514 | 515 | IStatementResult result = ExecuteQuery(query.ToString()); 516 | 517 | return result.Map(); 518 | } 519 | 520 | public bool Drop(string uuid) where T : EntityBase, new() 521 | { 522 | if (string.IsNullOrWhiteSpace(uuid)) 523 | throw new ArgumentNullException("uuid"); 524 | 525 | var query = new StringFormatter(QueryTemplates.TEMPLATE_DROP); 526 | query.Add("@label", new T().Label); 527 | query.Add("@Uuid", uuid); 528 | 529 | IStatementResult result = ExecuteQuery(query.ToString()); 530 | 531 | return result.Summary.Counters.NodesDeleted == 1; 532 | } 533 | 534 | public int DropByProperties(Dictionary props) where T : EntityBase, new() 535 | { 536 | if (props == null || !props.Any()) 537 | throw new ArgumentNullException("props"); 538 | 539 | dynamic properties = props.AsQueryClause(); 540 | dynamic clause = properties.clause; 541 | Dictionary parameters = properties.parameters; 542 | 543 | var query = new StringFormatter(QueryTemplates.TEMPLATE_DROP_BY_PROPERTIES); 544 | query.Add("@label", new T().Label); 545 | query.Add("@clause", clause); 546 | 547 | IStatementResult result = ExecuteQuery(query.ToString(), parameters); 548 | 549 | return result.Summary.Counters.NodesDeleted; 550 | } 551 | 552 | public IList GetByProperty( 553 | string propertyName, 554 | object propertValue) where T : EntityBase, new() 555 | { 556 | if (string.IsNullOrWhiteSpace(propertyName)) 557 | throw new ArgumentNullException("propertyName"); 558 | 559 | if (propertValue == null) 560 | throw new ArgumentNullException("propertValue"); 561 | 562 | var entites = new Lazy>(); 563 | 564 | var query = new StringFormatter(QueryTemplates.TEMPLATE_GET_BY_PROPERTY); 565 | query.Add("@label", new T().Label); 566 | query.Add("@property", propertyName); 567 | query.Add("@result", TAG); 568 | query.Add("@relatedNode", string.Empty); 569 | query.Add("@relationship", string.Empty); 570 | 571 | IStatementResult result = ExecuteQuery(query.ToString(), new { value = propertValue }); 572 | 573 | foreach (IRecord record in result) 574 | { 575 | var node = record[0].As().Properties; 576 | 577 | var relatedNodes = FetchRelatedNode(node["Uuid"].ToString()); 578 | 579 | var nodes = node.Concat(relatedNodes).ToDictionary(x => x.Key, x => x.Value); 580 | 581 | T nodeObject = nodes.Map(); 582 | 583 | entites.Value.Add(nodeObject); 584 | } 585 | 586 | return entites.Value; 587 | } 588 | 589 | public IList GetByProperties(Dictionary entity) where T : EntityBase, new() 590 | { 591 | if (entity == null) 592 | throw new ArgumentNullException("entity"); 593 | 594 | dynamic properties = entity.AsQueryClause(); 595 | dynamic clause = properties.clause; 596 | Dictionary parameters = properties.parameters; 597 | 598 | var entites = new Lazy>(); 599 | 600 | var query = new StringFormatter(QueryTemplates.TEMPLATE_GET_BY_PROPERTIES); 601 | query.Add("@label", new T().Label); 602 | query.Add("@clause", clause); 603 | query.Add("@result", TAG); 604 | query.Add("@relatedNode", string.Empty); 605 | query.Add("@relationship", string.Empty); 606 | 607 | IStatementResult result = ExecuteQuery(query.ToString(), parameters); 608 | 609 | foreach (IRecord record in result) 610 | { 611 | var node = record[0].As().Properties; 612 | 613 | var relatedNodes = FetchRelatedNode(node["Uuid"].ToString()); 614 | 615 | var nodes = node.Concat(relatedNodes).ToDictionary(x => x.Key, x => x.Value); 616 | 617 | T nodeObject = Mapper.Map(nodes); 618 | 619 | entites.Value.Add(nodeObject); 620 | } 621 | 622 | return entites.Value; 623 | } 624 | 625 | public T GetByUuidWithRelatedNodes(string uuid) where T : EntityBase, new() 626 | { 627 | if (string.IsNullOrWhiteSpace(uuid)) 628 | throw new ArgumentNullException("uuid"); 629 | 630 | var query = new StringFormatter(QueryTemplates.TEMPLATE_GET_BY_PROPERTY); 631 | query.Add("@label", new T().Label); 632 | query.Add("@property", "Uuid"); 633 | query.Add("@result", TAG); 634 | query.Add("@relatedNode", string.Empty); 635 | query.Add("@relationship", string.Empty); 636 | 637 | IStatementResult result = ExecuteQuery(query.ToString(), new { value = uuid }); 638 | 639 | IReadOnlyDictionary node = result.FirstOrDefault()?[0].As().Properties; 640 | 641 | if (node == null) 642 | return default; 643 | 644 | IReadOnlyDictionary nodes; 645 | 646 | IDictionary relatedNodes = FetchRelatedNode(uuid); 647 | 648 | if (relatedNodes == null || !relatedNodes.Any()) 649 | { 650 | nodes = node.ToDictionary(x => x.Key, x => x.Value); 651 | } 652 | else 653 | { 654 | nodes = node.Concat(relatedNodes).ToDictionary(x => x.Key, x => x.Value); 655 | } 656 | 657 | T entity = Mapper.Map(nodes); 658 | 659 | return entity; 660 | } 661 | 662 | public IList GetAll(string where = default) where T : EntityBase, new() 663 | { 664 | var entites = new Lazy>(); 665 | 666 | var query = new StringFormatter(QueryTemplates.TEMPLATE_GET_ALL); 667 | query.Add("@label", new T().Label); 668 | query.Add("@result", TAG); 669 | query.Add("@where", string.IsNullOrWhiteSpace(where) ? string.Empty : $"WHERE {where}"); 670 | 671 | IStatementResult result = ExecuteQuery(query.ToString()); 672 | 673 | foreach (IRecord record in result) 674 | { 675 | IReadOnlyDictionary node = record[0].As().Properties; 676 | 677 | string uuid = node["Uuid"].ToString(); 678 | 679 | var relatedNodes = FetchRelatedNode(uuid); 680 | 681 | var nodes = node.Concat(relatedNodes).ToDictionary(x => x.Key, x => x.Value); 682 | 683 | T nodeObject = Mapper.Map(nodes); 684 | 685 | entites.Value.Add(nodeObject); 686 | } 687 | 688 | return entites.Value; 689 | } 690 | 691 | public IList RunCustomQuery( 692 | string query, 693 | Dictionary parameters = null) where T : class, new() 694 | { 695 | if (string.IsNullOrWhiteSpace(query)) 696 | throw new ArgumentNullException("query"); 697 | 698 | var entites = new Lazy>(); 699 | 700 | IStatementResult result = ExecuteQuery(query, parameters); 701 | 702 | foreach (IRecord record in result) 703 | { 704 | T nodeObject = Mapper.Map, T>(record.Values); 705 | 706 | entites.Value.Add(nodeObject); 707 | } 708 | 709 | return entites.Value; 710 | } 711 | 712 | public IStatementResult RunCustomQuery( 713 | string query, 714 | Dictionary parameters = null) 715 | { 716 | if (string.IsNullOrWhiteSpace(query)) 717 | throw new ArgumentNullException("query"); 718 | 719 | IStatementResult result = ExecuteQuery(query, parameters); 720 | 721 | return result; 722 | } 723 | 724 | public bool AddLabel( 725 | string uuid, 726 | string labelName) 727 | { 728 | if (string.IsNullOrWhiteSpace(uuid)) 729 | throw new ArgumentNullException("uuid"); 730 | 731 | if (string.IsNullOrWhiteSpace(labelName)) 732 | throw new ArgumentNullException("labelName"); 733 | 734 | var query = new StringFormatter(QueryTemplates.TEMPLATE_ADD_LABEL); 735 | query.Add("@Uuid", uuid); 736 | query.Add("@label", labelName); 737 | 738 | IStatementResult result = ExecuteQuery(query.ToString()); 739 | 740 | if (result.Summary.Counters.LabelsAdded == 0) 741 | throw new Exception("Label creation error!"); 742 | 743 | return result.Summary.Counters.LabelsAdded == 1; 744 | } 745 | 746 | public bool Ping() 747 | { 748 | IStatementResult result = ExecuteQuery("RETURN 1"); 749 | 750 | return result.FirstOrDefault()?[0].As() == 1; 751 | } 752 | 753 | #region Commented Methods 754 | //public List GetRelatedNodesByID(int id) where T : EntityBase, new() 755 | // where T2 : EntityBase, new() 756 | //{ 757 | // if (id <= 0) 758 | // throw new ArgumentException("id"); 759 | 760 | // var entities = new List(); 761 | // string labelName = new T().Label; 762 | // string labelNameRelatedNode = new T2().Label; 763 | 764 | // IStatementResult result = ExecuteQuery(string.Format(@"MATCH ({0})--({1}) WHERE ID({0}) = $id RETURN {1}", labelName, labelNameRelatedNode), new { id }); 765 | 766 | // foreach (IRecord record in result) 767 | // { 768 | // T2 nodeObject = Mapper.Map, T2>(record[labelNameRelatedNode].As().Properties); 769 | 770 | // entities.Add(nodeObject); 771 | // } 772 | 773 | // return entities; 774 | //} 775 | 776 | //public IDictionary GetAllWithRelationship(T2 rel, string relName) where T : EntityBase, new() 777 | // where T2 : EntityBase, new() 778 | //{ 779 | // IDictionary entites = new Dictionary(); 780 | 781 | // IStatementResult result = ExecuteQuery(string.Format(@"MATCH (n:{0}) OPTIONAL MATCH (n)-[r:" + relName + "]->(r:{1}) RETURN n,r", new T().Label, new T2().Label)); 782 | 783 | // foreach (IRecord record in result) 784 | // { 785 | // IReadOnlyDictionary node = record[PREFIX_QUERY_RESPONSE_KEY].As().Properties; 786 | 787 | // entites.Add(node.ToObject()); 788 | // } 789 | 790 | // return entites; 791 | //} 792 | #endregion 793 | } 794 | } --------------------------------------------------------------------------------