timschreiber / dapperunitofwork Goto Github PK
View Code? Open in Web Editor NEWUnit of Work and Repository Example for Dapper
License: MIT License
Unit of Work and Repository Example for Dapper
License: MIT License
Hi Tim,
I learn a lot using UoW with dapper from your code. Thank you very much.
This is not an issue anyway, if we just want to add cat without adding new breed (no transaction) do we still need to insert to database via UoW or can we just add save/commit method on repository with IDBtransaction injected to constructor?
Thanks.
`using(var uow = new UnitOfWork("LosGatos"))
{
var orangeMackerel = uow.BreedRepository.FindByName("Orange Mackerel");
**if(orangeMackerel == null) uow.rollback();**
var morris = new Cat { BreedId = orangeMackerel.BreedId, Name = "Morris", Age = 12 };
uow.CatRepository.Add(morris);
uow.Commit();
}`
Hi Tim,
I've tried DapperUnitOfWork and all is well so far. But when testing I encountered an InvalidOperationException due to the connection not being closed. I fixed that with a change in the UnitOfWork.ctor on line 24 of UnitOfWork.cs:
/*24*/ //_connection.Open();
/*25*/ if (_connection.State == ConnectionState.Closed) _connection.Open(); // new
Kind regards,
Manfred
Since visual studio 2017 fires an error at BreedRepository regarding RepositoryBase not being accessible (internal abstract), is it recommended to make RepositoryBase more accessible with public abstract class RepositoryBase
?
Look for some help :)
I have multiple stored procedures in MS SQL Server which in themselves are defined as transactions.
In my repository I want to call multiple ExecuteAsync() on stored procedures but for them to be wrapped in a unit of work.
I have managed to implement the transaction for each individual use of ExecuteAsync() but not to wrap them up as a unit pf work.
public async Task UpdateCatName(CatNameUpdateDbModel chat)
{
if (cat == null)
throw new ArgumentNullException(nameof(cat));
// start Unit Of Work
await _dbClient.ExecuteAsync(DbConstants.SpUpdateCatName,
new
{
catName = cat.CatName,
},
DbConstants.DbConnectionTimeout,
CommandType.StoredProcedure,
Transaction);
await _dbClient.ExecuteAsync(DbConstants.SpUpdateCatNameAuditLog,
new
{
catNameAuditLog = cat.CatNameAuditLog,
},
DbConstants.DbConnectionTimeout,
CommandType.StoredProcedure,
Transaction);
// End Unit Of Work
// If either Stored procedure is not successfully completed then bother are rolled back
}
I think it would be better to create and open the connection at the first access to a repository. This is to avoid that you get an exception when you use Dependency Injection at the object creation, but also exceptions in constructor should generally be avoided.
I have done a similar implementation to your UnitOfWork. See link below
https://github.com/mortenbrudvik/SQLiteDapperConsole/blob/main/Infrastructure/UnitOfWork.cs
2017-02-15 16:12:45,519 DEBUG Error occurred during execution of 'Worker #4021037f' process. Execution will be retried (attempt 1 of 2147483647) in 00:00:00 seconds.
System.InvalidOperationException: Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource
1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource
1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
In my code
using (var uow = new UnitOfWork())
{
// GET USER FROM DATABASE
var user = uow.LoginRepository.Get(email);
// CREATE NEW ENTITY
var entity = new FriendsEmail();
entity.xxx = 1;
entity.yyy = 2;
// SAVE EMAILS
uow.FriendsEmailRepository.Add(entity);
uow.Commit();
}
Any ideia?
Can it be because of this?
~UnitOfWork()
{
dispose(false);
}
why dispose(false)?
Thank you,
Pedro Adão
Hi I want to know that does connection.execute methods trips to database.?
Not sure of the history on the false attribution thing, but just to say that lucask's answer on stack overflow is currently just a link to this repository. It now just looks like he's just providing a new link to your repo in response to adaam's comment about a dead link in the comment above?
Anyway, either way, the comment's about this in your readme are probably redundant now?
Just a suggestion to move all common operations in generic base repository.
Your thoughts on this.
public class BaseRepository<TEntity> : IDisposable, IBaseRepository<TEntity> where TEntity : class
{
protected readonly SqlConnection conn;
public BaseRepository()
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
conn = new SqlConnection(config.GetConnectionString("DefaultConnection"));
}
public void Add(TEntity obj)
{
conn.Insert(obj);
}
public void Dispose()
{
conn.Dispose();
}
public TEntity FindById(int id)
{
throw new NotImplementedException();
}
public IEnumerable<TEntity> GetAll()
{
//var selectQuery = "SELECT * FROM Test";
var payloads = conn.GetAll<TEntity>().ToList();
return payloads;
}
public void Remove(TEntity obj)
{
throw new NotImplementedException();
}
public void Update(TEntity obj)
{
throw new NotImplementedException();
}
}
@timschreiber your repository is a really clear explanation of unit of work and I would like to use parts of it.
What is the license this code is under?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.