Olá
Recentemente comecei a trabalhar com mongo em projetos dotnet. Para quem ainda não se "aventurou" com bancos não relacionais e dotnet, posso dizer que é muito fácil e tranquilo realizar as implementações e de quebra ganhar em performance de consulta.
Para poder trabalhar com mongo em dotnet você precisa incluir o driver do mongo. Existe um drive oficial que pode ser baixado via nuget. Nos exemplos a seguir foi utilizado a versão 2.4.4 do drive, mas enquanto escreve este post já esta disponível a versão 2.5.0 com melhorias, porém mais dependências.
Para poder trabalhar com mongo em dotnet você precisa incluir o driver do mongo. Existe um drive oficial que pode ser baixado via nuget. Nos exemplos a seguir foi utilizado a versão 2.4.4 do drive, mas enquanto escreve este post já esta disponível a versão 2.5.0 com melhorias, porém mais dependências.
Para criar o template repositório com métodos para inserir, alterar, remover e consultar pode ser utilizado uma classe como a seguir:
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
using MongoDB.Bson; | |
using MongoDB.Driver; | |
using System.Collections.Generic; | |
using System.Configuration; | |
using System.Linq; | |
using System.Threading.Tasks; | |
namespace DotNet.Mongo.Repository.Repositorios | |
{ | |
public class BaseRepositorio<TColecao> | |
{ | |
protected static IMongoClient Client => new MongoClient(ConfigurationManager.ConnectionStrings["conexao"].ConnectionString); | |
protected static IMongoDatabase Db => Client.GetDatabase(ConfigurationManager.AppSettings["database"]); | |
protected static IMongoCollection<TColecao> Colecao; | |
public BaseRepositorio(string colecao) | |
{ | |
Colecao = Db.GetCollection<TColecao>(colecao); | |
} | |
/// <summary> | |
/// Obter por Id | |
/// </summary> | |
/// <param name="id"></param> | |
/// <returns></returns> | |
public virtual TColecao Obter(string id) | |
{ | |
return Colecao.Find(FiltroPorId(id)).FirstOrDefault(); | |
} | |
public virtual IQueryable<TColecao> Obter() | |
{ | |
return Colecao.AsQueryable(); | |
} | |
/// <summary> | |
/// Inserir varios registros | |
/// </summary> | |
/// <param name="modelo"></param> | |
public virtual void Inserir(IList<TColecao> modelo) | |
{ | |
Colecao.InsertMany(modelo); | |
} | |
/// <summary> | |
/// Inserir um registro | |
/// </summary> | |
/// <param name="modelo"></param> | |
public virtual void Inserir(TColecao modelo) | |
{ | |
Colecao.InsertOne(modelo); | |
} | |
public virtual async Task InserirAsync(IList<TColecao> modelo) | |
{ | |
await Colecao.InsertManyAsync(modelo); | |
} | |
public virtual async Task InserirAsync(TColecao modelo) | |
{ | |
await Colecao.InsertOneAsync(modelo); | |
} | |
public virtual void Atualizar(TColecao modelo) | |
{ | |
Colecao.ReplaceOne(FiltroPorId(BsonTypeMapper.MapToDotNetValue(modelo.ToBsonDocument().GetElement("_id").Value).ToString()), modelo); | |
} | |
public virtual void Remover(string id) | |
{ | |
Colecao.DeleteOne(FiltroPorId(id)); | |
} | |
protected FilterDefinition<TColecao> FiltroPorId(string id) | |
{ | |
return Builders<TColecao>.Filter.Eq("_id", new ObjectId(id)); | |
} | |
} | |
} |
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
using DotNet.Mongo.Repository.Entidades; | |
namespace DotNet.Mongo.Repository.Repositorios | |
{ | |
public class ContatoRepositorio : BaseRepositorio<Contato> | |
{ | |
public ContatoRepositorio() : base("contato") | |
{ | |
} | |
} | |
} |
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
var contatoRepositorio = new ContatoRepositorio(); | |
var contato = new Contato() | |
{ | |
Nome = "Teste", | |
Telefone = new Collection<Telefone>() | |
{ | |
new Telefone{ Ddd=47,Numero=989085525, Tipo=Enumeradores.TipoTelefone.Celular} | |
} | |
}; | |
contatoRepositorio.Inserir(contato); |
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
<?xml version="1.0" encoding="utf-8" ?> | |
<configuration> | |
<connectionStrings> | |
<add name="conexao" connectionString="mongodb://localhost:27017" /> | |
</connectionStrings> | |
<appSettings> | |
<add key="database" value="agenda" /> | |
</appSettings> | |
</configuration> |
O fonte pode ser encontrado em:
Diretório:
Excelente explicação, muito obrigado por sua ajuda!
ResponderExcluir