Skip to content

Commit

Permalink
added async support
Browse files Browse the repository at this point in the history
  • Loading branch information
dj-nitehawk committed Apr 19, 2019
1 parent 5bfc9e7 commit 4628aa9
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 9 deletions.
17 changes: 15 additions & 2 deletions DemoConsole/Program.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
using System;
using DemoConsole.Models;
using System.Threading.Tasks;
//using MongoDB.Driver;
//using MongoDB.Driver.Linq;
//using MongoDAL;

namespace DemoConsole
{
class Program
{
static void Main(string[] args)
static async Task Main(string[] args)
{
//INITIALIZE - Basic
new MongoDAL.DB("Demo");
Expand All @@ -30,6 +33,9 @@ static void Main(string[] args)

person.Save();

//CREATE Async
//await DB.SaveAsync<Person>(person);

var address = new Address
{
Line1 = "line 1",
Expand All @@ -42,6 +48,11 @@ static void Main(string[] args)
//READ
var lastPerson = person.FindLast();

//READ Async
//var lastPerson = await DB.Collection<Person>()
// .OrderByDescending(p=> p.ModifiedOn)
// .FirstOrDefaultAsync();

//UPDATE
lastPerson.Name = "Updated at " + DateTime.UtcNow.ToString();
lastPerson.Save();
Expand All @@ -50,8 +61,10 @@ static void Main(string[] args)
//lastPerson.Delete();
//address.DeleteByOwnerId(lastPerson.Id);

//DELETE Async
//await DB.DeleteAsync<Person>(lastPerson.Id);

Console.WriteLine("CRUD Complete...");
Console.ReadKey();
}
}
}
2 changes: 1 addition & 1 deletion MongoDAL/MongoDAL.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<Description>An easy to use Data Access Layer for .Net Core applications to use LINQ with MongoDB.</Description>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageProjectUrl>https://github.com/dj-nitehawk/MongoDAL</PackageProjectUrl>
<Version>2.0</Version>
<Version>2.5</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
44 changes: 41 additions & 3 deletions MongoDAL/MongoDB.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using MongoDB.Driver.Linq;
using System.Linq.Expressions;
using MongoDB.Bson.Serialization.Conventions;
using System.Threading.Tasks;

namespace MongoDAL
{
Expand All @@ -20,7 +21,7 @@ public class DB
/// <param name="database">Name of the database</param>
/// <param name="host">Adderss of the MongoDB server</param>
/// <param name="port">Port number of the server</param>
public DB(string database, string host ="127.0.0.1", int port = 27017)
public DB(string database, string host = "127.0.0.1", int port = 27017)
{

Initialize(
Expand Down Expand Up @@ -89,9 +90,7 @@ public static IMongoQueryable<T> Collection<T>()
public static void Save<T>(T entity) where T : MongoEntity
{
CheckIfInitialized();

if (string.IsNullOrEmpty(entity.Id)) entity.Id = ObjectId.GenerateNewId().ToString();

entity.ModifiedOn = DateTime.UtcNow;

collection<T>().ReplaceOne(
Expand All @@ -100,6 +99,23 @@ public static void Save<T>(T entity) where T : MongoEntity
new UpdateOptions() { IsUpsert = true });
}

/// <summary>
/// Persists an entity to MongoDB
/// </summary>
/// <typeparam name="T">Any class that inherits from MongoEntity</typeparam>
/// <param name="entity">The instance to persist</param>
public static Task SaveAsync<T>(T entity) where T : MongoEntity
{
CheckIfInitialized();
if (string.IsNullOrEmpty(entity.Id)) entity.Id = ObjectId.GenerateNewId().ToString();
entity.ModifiedOn = DateTime.UtcNow;

return collection<T>().ReplaceOneAsync(
x => x.Id.Equals(entity.Id),
entity,
new UpdateOptions() { IsUpsert = true });
}

/// <summary>
/// Deletes a single entity from MongoDB
/// </summary>
Expand All @@ -112,6 +128,17 @@ public static void Delete<T>(string id) where T : MongoEntity
collection<T>().DeleteOne(x => x.Id.Equals(id));
}

/// <summary>
/// Deletes a single entity from MongoDB
/// </summary>
/// <typeparam name="T">Any class that inherits from MongoEntity</typeparam>
/// <param name="id">The Id of the entity to delete</param>
public static Task DeleteAsync<T>(string id)where T : MongoEntity
{
CheckIfInitialized();
return collection<T>().DeleteOneAsync(x=> x.Id.Equals(id));
}

/// <summary>
/// Delete multiple entities from MongoDB
/// </summary>
Expand All @@ -124,6 +151,17 @@ public static void DeleteMany<T>(Expression<Func<T, bool>> expression) where T :
collection<T>().DeleteMany(expression);
}

/// <summary>
/// Delete multiple entities from MongoDB
/// </summary>
/// <typeparam name="T">Any class that inherits from MongoEntity</typeparam>
/// <param name="expression">A lambda expression for matching entities to delete.</param>
public static Task DeleteManyAsync<T>(Expression<Func<T, bool>> expression) where T : MongoEntity
{
CheckIfInitialized();
return collection<T>().DeleteManyAsync(expression);
}

private static void CheckIfInitialized()
{
if (_db == null)
Expand Down
15 changes: 12 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
# MongoDAL
An easy to use Data Access Layer for .Net Core applications to use LINQ with MongoDB.

## How To Use

## Install
install nuget package with the command: `Install-Package MongoDAL`

Expand Down Expand Up @@ -77,7 +75,7 @@ when updating entities, if an entity with a matching `Id` is found in the databa
linq queries can be written against any entity collection in mongodb like so:
```csharp
var myAddress = (from a in DB.Collection<Address>()
where a.City.Contains("123")
where a.Street.Contains("123")
select a).SingleOrDefault();
```
most linq operations are available. check out the mongodb [c# driver linq documentation](http://mongodb.github.io/mongo-csharp-driver/2.7/reference/driver/crud/linq/) for more details.
Expand Down Expand Up @@ -127,6 +125,17 @@ if there are properties of your entities that you don't want persisted to mongod
}
```

## Async Support
async overloads are available for all provided methods.

in order to write queries against collections, make sure to import the mongodb linq extensions with `using MongoDB.Driver.Linq;` and write queries as follows:

```csharp
var latsPerson = await (from p in DB.Collection<Person>()
orderby p.ModifiedOn descending
select p).FirstOrDefaultAsync();
```

## Examples
[click here](https://github.com/dj-nitehawk/MongoDAL/blob/master/DemoConsole/Program.cs) for basic examples.

Expand Down

0 comments on commit 4628aa9

Please sign in to comment.