-
-
Save diegofrata/4394128 to your computer and use it in GitHub Desktop.
Very Simple MongoDB Repository for F#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
open System.Collections | |
open System.Configuration | |
open System.Data.Entity.Design.PluralizationServices | |
open System.Linq | |
open FluentMongo.Linq | |
open MongoDB.Bson | |
open MongoDB.Driver | |
open MongoDB.Driver.Builders | |
module MongoRepository = | |
let mutable connectionStringName = "MongoDB" | |
let private db = | |
let connectionString = ConfigurationManager.ConnectionStrings.[connectionStringName].ConnectionString | |
MongoConnectionStringBuilder(connectionString) |> MongoDatabase.Create | |
let private collection<'a> = | |
let pluralizer = PluralizationService.CreateService(System.Globalization.CultureInfo.CurrentCulture) | |
let n = typedefof<'a>.Name |> pluralizer.Pluralize | |
db.GetCollection<'a> n | |
let qry<'a> : IQueryable<'a> = | |
collection |> MongoCollectionExtensions.AsQueryable | |
let save item = | |
item |> collection.Save |> ignore | |
let removeById<'a> id = | |
let value = id |> BsonValue.Create | |
Query.EQ ("_id", value) | |
|> collection<'a>.Remove | |
|> ignore | |
let inline remove<'a when 'a : (member Id : ObjectId)> item = | |
(^a : (member Id : ObjectId) item) |> removeById | |
module RepositoryTest = | |
[<CLIMutable>] | |
type User = { Id : ObjectId; Name : string; Age : int; } | |
[<CLIMutable>] | |
type Place = { Id : ObjectId; Name : string; Address : string; } | |
let saveTest () = | |
{ Id = ObjectId.Empty; Name = "Diego Frata"; Age = 25 } |> MongoRepository.save | |
{ Id = ObjectId.Empty; Name = "Mundo Cervejeiro"; Address = "Av. Miruna, 51" } |> MongoRepository.save | |
let queryTest () = | |
query { for u in MongoRepository.qry<User> do | |
select u } | |
|> Seq.iter (fun u -> printf "%A %s %d" u.Id u.Name u.Age) | |
let removeTest () = | |
query { for u in MongoRepository.qry<User> do | |
select u | |
take 1 } | |
|> Seq.iter (fun u -> MongoRepository.remove u) | |
[<EntryPoint>] | |
let main argv = | |
do saveTest() | |
do queryTest() | |
do removeTest() | |
0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This repository is intended to be used in projects where ONLY ONE MongoBD database is accessed. Imposing this limit creates the ability to implement the repository as module, making it simple to use.