Skip to content

Commit ca4591f

Browse files
committed
Aggiornamento Mongo DB
1 parent 6e63f48 commit ca4591f

12 files changed

Lines changed: 187 additions & 102 deletions

File tree

SharpRepository.MongoDbRepository/MongoDbRepositoryBase.cs

Lines changed: 86 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -9,37 +9,38 @@
99
using MongoDB.Bson.Serialization.IdGenerators;
1010
using MongoDB.Bson.Serialization.Options;
1111
using MongoDB.Driver;
12-
using MongoDB.Driver.Builders;
1312
using MongoDB.Driver.Linq;
1413
using SharpRepository.Repository;
1514
using SharpRepository.Repository.Caching;
1615
using SharpRepository.Repository.FetchStrategies;
1716
using SharpRepository.Repository.Helpers;
1817
using SharpRepository.Repository.Specifications;
18+
using MongoDB.Bson.Serialization.Serializers;
1919

2020
namespace SharpRepository.MongoDbRepository
2121
{
2222
public class MongoDbRepositoryBase<T, TKey> : LinqRepositoryBase<T, TKey> where T : class, new()
2323
{
2424
private readonly string _databaseName;
25-
protected MongoDatabase Database;
26-
protected MongoServer Server;
27-
28-
private readonly Dictionary<Type, BsonType> _keyTypeToBsonType = new Dictionary<Type, BsonType>
29-
{
30-
{typeof(string), BsonType.String},
31-
{typeof(Guid), BsonType.ObjectId},
32-
{typeof(ObjectId), BsonType.ObjectId},
33-
{typeof(byte[]), BsonType.ObjectId}
34-
};
35-
36-
private readonly Dictionary<Type, IIdGenerator> _keyTypeToBsonGenerator = new Dictionary<Type, IIdGenerator>
37-
{
38-
{typeof (string), new StringObjectIdGenerator() },
39-
{typeof (Guid), new GuidGenerator()},
40-
{typeof (ObjectId), new ObjectIdGenerator()},
41-
{typeof(byte[]), new BsonBinaryDataGuidGenerator(GuidRepresentation.Standard)}
42-
};
25+
protected IMongoDatabase Database;
26+
27+
private readonly Dictionary<Type, BsonType> _keyTypeToBsonType =
28+
new Dictionary<Type, BsonType>
29+
{
30+
{typeof(string), BsonType.String},
31+
{typeof(Guid), BsonType.ObjectId},
32+
{typeof(ObjectId), BsonType.ObjectId},
33+
{typeof(byte[]), BsonType.ObjectId}
34+
};
35+
36+
private readonly Dictionary<Type, IIdGenerator> _keyTypeToBsonGenerator =
37+
new Dictionary<Type, IIdGenerator>
38+
{
39+
{typeof (string), new StringObjectIdGenerator() },
40+
{typeof (Guid), new GuidGenerator()},
41+
{typeof (ObjectId), new ObjectIdGenerator()},
42+
{typeof(byte[]), new BsonBinaryDataGuidGenerator(GuidRepresentation.Standard)}
43+
};
4344

4445
internal MongoDbRepositoryBase(ICachingStrategy<T, TKey> cachingStrategy = null)
4546
: base(cachingStrategy)
@@ -51,50 +52,51 @@ internal MongoDbRepositoryBase(string connectionString, ICachingStrategy<T, TKey
5152
: base(cachingStrategy)
5253
{
5354
_databaseName = MongoUrl.Create(connectionString).DatabaseName;
54-
Initialize(new MongoClient(connectionString).GetServer());
55+
var cli = new MongoClient(connectionString);
56+
Initialize(cli.GetDatabase(_databaseName));
5557
}
5658

57-
internal MongoDbRepositoryBase(MongoServer mongoServer, ICachingStrategy<T, TKey> cachingStrategy = null)
59+
internal MongoDbRepositoryBase(IMongoDatabase mongoDatabase, ICachingStrategy<T, TKey> cachingStrategy = null)
5860
: base(cachingStrategy)
5961
{
60-
Initialize(mongoServer);
62+
Initialize(mongoDatabase);
6163
}
6264

6365
private string DatabaseName
6466
{
6567
get { return string.IsNullOrEmpty(_databaseName) ? TypeName : _databaseName; }
6668
}
6769

68-
private void Initialize(MongoServer mongoServer = null)
70+
private void Initialize(IMongoDatabase mongoDatabase = null)
6971
{
70-
Server = mongoServer ?? new MongoClient("mongodb://localhost").GetServer();
71-
Database = Server.GetDatabase(DatabaseName);
72+
Database = mongoDatabase ?? new MongoClient("mongodb://localhost").GetDatabase(MongoUrl.Create("mongodb://localhost").DatabaseName);
7273

7374
if (!BsonClassMap.IsClassMapRegistered(typeof (T)))
7475
{
7576
var primaryKeyPropInfo = GetPrimaryKeyPropertyInfo();
7677
var primaryKeyName = primaryKeyPropInfo.Name;
7778

7879
BsonClassMap.RegisterClassMap<T>(cm =>
79-
{
80-
cm.AutoMap();
81-
if (cm.IdMemberMap == null)
82-
{
83-
cm.SetIdMember(cm.GetMemberMap(primaryKeyName));
84-
85-
if (_keyTypeToBsonType.ContainsKey(typeof(TKey)) && (_keyTypeToBsonGenerator.ContainsKey(typeof(TKey))))
86-
{
87-
cm.IdMemberMap.SetRepresentation(_keyTypeToBsonType[typeof(TKey)]);
88-
cm.IdMemberMap.SetIdGenerator(_keyTypeToBsonGenerator[typeof(TKey)]);
89-
}
90-
}
91-
92-
cm.Freeze();
93-
});
80+
{
81+
cm.AutoMap();
82+
if (cm.IdMemberMap == null)
83+
{
84+
cm.SetIdMember(cm.GetMemberMap(primaryKeyName));
85+
86+
if (_keyTypeToBsonType.ContainsKey(typeof(TKey)) && (_keyTypeToBsonGenerator.ContainsKey(typeof(TKey))))
87+
{
88+
cm.IdMemberMap.SetSerializer(new StringSerializer(_keyTypeToBsonType[typeof(TKey)]));
89+
cm.IdMemberMap.SetIdGenerator(_keyTypeToBsonGenerator[typeof(TKey)]);
90+
}
91+
}
92+
93+
cm.Freeze();
94+
}
95+
);
9496
}
9597
}
9698

97-
private MongoCollection<T> BaseCollection()
99+
private IMongoCollection<T> BaseCollection()
98100
{
99101
return Database.GetCollection<T>(TypeName);
100102
}
@@ -106,11 +108,13 @@ protected override IQueryable<T> BaseQuery(IFetchStrategy<T> fetchStrategy = nul
106108

107109
protected override T GetQuery(TKey key, IFetchStrategy<T> fetchStrategy)
108110
{
109-
var keyBsonType = ((RepresentationSerializationOptions)BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.SerializationOptions).Representation;
110-
111-
return IsValidKey(key)
112-
? BaseCollection().FindOneById(BsonTypeMapper.MapToBsonValue(key, keyBsonType))
113-
: default(T);
111+
var keyBsonType = ((StringSerializer)BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.GetSerializer()).Representation;
112+
var keyMemberName = BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.MemberName;
113+
if (IsValidKey(key)) {
114+
var keyBsonValue = BsonTypeMapper.MapToBsonValue(key, keyBsonType);
115+
var filter = Builders<T>.Filter.Eq(keyMemberName, keyBsonValue);
116+
return BaseCollection().Find(filter).FirstOrDefault();
117+
} else return default(T);
114118
}
115119

116120
public override int Sum(ISpecification<T> criteria, Expression<Func<T, int>> selector)
@@ -295,7 +299,7 @@ public override double Average(ISpecification<T> criteria, Expression<Func<T, lo
295299

296300
protected override void AddItem(T entity)
297301
{
298-
BaseCollection().Insert(entity);
302+
BaseCollection().InsertOne(entity);
299303
}
300304

301305
protected override void DeleteItem(T entity)
@@ -305,15 +309,46 @@ protected override void DeleteItem(T entity)
305309

306310
if (IsValidKey(pkValue))
307311
{
308-
var keyMemberMap = BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap;
309-
var keyBsonType = ((RepresentationSerializationOptions)keyMemberMap.SerializationOptions).Representation;
310-
BaseCollection().Remove(Query.EQ(keyMemberMap.ElementName, BsonTypeMapper.MapToBsonValue(pkValue, keyBsonType)));
312+
var keyPropertyName = BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.ElementName;
313+
var keyPair = GetMongoProperty(entity, keyPropertyName);
314+
var filter = Builders<T>.Filter.Eq(keyPair.Key, keyPair.Value);
315+
316+
BaseCollection().DeleteOne(filter);
311317
}
312318
}
313319

314320
protected override void UpdateItem(T entity)
315321
{
316-
BaseCollection().Save(entity);
322+
TKey pkValue;
323+
GetPrimaryKey(entity, out pkValue);
324+
if (IsValidKey(pkValue))
325+
{
326+
var keyPropertyName = BsonClassMap.LookupClassMap(typeof(T)).IdMemberMap.ElementName;
327+
var keyPair = GetMongoProperty(entity, keyPropertyName);
328+
var filter = Builders<T>.Filter.Eq(keyPair.Key, keyPair.Value);
329+
330+
331+
var bsonMembers = BsonClassMap.LookupClassMap(typeof(T)).AllMemberMaps.Where(m => m.MemberName != keyPropertyName);
332+
var updates = new List<UpdateDefinition<T>>();
333+
foreach (var members in bsonMembers)
334+
{
335+
var propPair = GetMongoProperty(entity, members.MemberName);
336+
updates.Add(Builders<T>.Update.Set(propPair.Key, propPair.Value));
337+
}
338+
339+
BaseCollection().UpdateOne(filter, Builders<T>.Update.Combine(updates));
340+
}
341+
342+
}
343+
344+
public static KeyValuePair<string, BsonValue> GetMongoProperty(T entity, string propertyName)
345+
{
346+
var value = typeof(T).GetProperty(propertyName).GetValue(entity);
347+
var memberMap = BsonClassMap.LookupClassMap(typeof(TKey)).GetMemberMap(propertyName);
348+
var keyBsonType = ((StringSerializer)memberMap.GetSerializer()).Representation;
349+
var bsonPropertyValue = BsonTypeMapper.MapToBsonValue(value, keyBsonType);
350+
351+
return new KeyValuePair<string, BsonValue>(propertyName, bsonPropertyValue);
317352
}
318353

319354
protected override void SaveChanges()
Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,16 @@
1+
using MongoDB.Bson;
12
using MongoDB.Driver;
23

34
namespace SharpRepository.MongoDbRepository
45
{
56
public static class MongoDbRepositoryManager
67
{
7-
public static bool ServerIsRunning(MongoServer server)
8+
public static bool ServerIsRunning(IMongoDatabase db)
89
{
910
try
1011
{
11-
server.Ping();
12+
db.RunCommandAsync((Command<BsonDocument>)"{ping:1}")
13+
.Wait();
1214
}
1315
catch
1416
{
@@ -20,7 +22,9 @@ public static bool ServerIsRunning(MongoServer server)
2022

2123
public static bool ServerIsRunning(string connectionString)
2224
{
23-
return ServerIsRunning(new MongoClient(connectionString).GetServer());
25+
var db_name = MongoUrl.Create(connectionString).DatabaseName;
26+
var cli = new MongoClient(connectionString);
27+
return ServerIsRunning(cli.GetDatabase(db_name));
2428
}
2529

2630
public static string DatabaseName(string connectionString)
@@ -30,9 +34,9 @@ public static string DatabaseName(string connectionString)
3034

3135
public static void DropDatabase(string connectionString)
3236
{
33-
var server = new MongoClient(connectionString).GetServer();
34-
var db = DatabaseName(connectionString);
35-
server.DropDatabase(db);
37+
var cli = new MongoClient(connectionString);
38+
var db_name = MongoUrl.Create(connectionString).DatabaseName;
39+
cli.DropDatabase(db_name);
3640
}
3741
}
3842
}

SharpRepository.MongoDbRepository/SharpRepository.MongoDbRepository.csproj

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,16 +34,22 @@
3434
<Prefer32Bit>false</Prefer32Bit>
3535
</PropertyGroup>
3636
<ItemGroup>
37-
<Reference Include="MongoDB.Bson, Version=1.11.0.92, Culture=neutral, PublicKeyToken=f686731cfb9cc103, processorArchitecture=MSIL">
38-
<HintPath>..\packages\mongocsharpdriver.1.11.0\lib\net35\MongoDB.Bson.dll</HintPath>
37+
<Reference Include="MongoDB.Bson, Version=2.4.3.23, Culture=neutral, processorArchitecture=MSIL">
38+
<HintPath>..\packages\MongoDB.Bson.2.4.3\lib\net45\MongoDB.Bson.dll</HintPath>
3939
</Reference>
40-
<Reference Include="MongoDB.Driver, Version=1.11.0.92, Culture=neutral, PublicKeyToken=f686731cfb9cc103, processorArchitecture=MSIL">
41-
<HintPath>..\packages\mongocsharpdriver.1.11.0\lib\net35\MongoDB.Driver.dll</HintPath>
40+
<Reference Include="MongoDB.Driver, Version=2.4.3.23, Culture=neutral, processorArchitecture=MSIL">
41+
<HintPath>..\packages\MongoDB.Driver.2.4.3\lib\net45\MongoDB.Driver.dll</HintPath>
42+
</Reference>
43+
<Reference Include="MongoDB.Driver.Core, Version=2.4.3.23, Culture=neutral, processorArchitecture=MSIL">
44+
<HintPath>..\packages\MongoDB.Driver.Core.2.4.3\lib\net45\MongoDB.Driver.Core.dll</HintPath>
4245
</Reference>
4346
<Reference Include="System" />
4447
<Reference Include="System.Configuration" />
4548
<Reference Include="System.Core" />
4649
<Reference Include="System.Data" />
50+
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
51+
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
52+
</Reference>
4753
</ItemGroup>
4854
<ItemGroup>
4955
<Compile Include="IAmInMongoDbRepository.cs" />
@@ -61,6 +67,7 @@
6167
</ProjectReference>
6268
</ItemGroup>
6369
<ItemGroup>
70+
<None Include="app.config" />
6471
<None Include="packages.config" />
6572
</ItemGroup>
6673
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<configuration>
3+
<runtime>
4+
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
5+
<dependentAssembly>
6+
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
7+
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
8+
</dependentAssembly>
9+
</assemblyBinding>
10+
</runtime>
11+
</configuration>
Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<packages>
3-
<package id="mongocsharpdriver" version="1.11.0" targetFramework="net452" />
3+
<package id="MongoDB.Bson" version="2.4.3" targetFramework="net452" />
4+
<package id="MongoDB.Driver" version="2.4.3" targetFramework="net452" />
5+
<package id="MongoDB.Driver.Core" version="2.4.3" targetFramework="net452" />
6+
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net452" />
47
</packages>

SharpRepository.Samples/SharpRepository.Samples.csproj

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@
3434
<Prefer32Bit>false</Prefer32Bit>
3535
</PropertyGroup>
3636
<ItemGroup>
37-
<Reference Include="nunit.framework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
38-
<HintPath>..\packages\NUnit.3.5.0\lib\net45\nunit.framework.dll</HintPath>
37+
<Reference Include="nunit.framework, Version=3.6.1.0, Culture=neutral, PublicKeyToken=2638cd05610744eb, processorArchitecture=MSIL">
38+
<HintPath>..\packages\NUnit.3.6.1\lib\net45\nunit.framework.dll</HintPath>
3939
</Reference>
4040
<Reference Include="Should, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
4141
<HintPath>..\packages\Should.1.1.20\lib\Should.dll</HintPath>
@@ -77,7 +77,9 @@
7777
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
7878
</ItemGroup>
7979
<ItemGroup>
80-
<None Include="packages.config" />
80+
<None Include="packages.config">
81+
<SubType>Designer</SubType>
82+
</None>
8183
</ItemGroup>
8284
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
8385
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
<?xml version="1.0" encoding="utf-8"?>
22
<packages>
3-
<package id="NUnit" version="3.5.0" targetFramework="net452" />
3+
<package id="NUnit" version="3.6.1" targetFramework="net452" />
44
<package id="Should" version="1.1.20" targetFramework="net452" />
55
</packages>

0 commit comments

Comments
 (0)