简体   繁体   中英

Entity Framework, Repository Pattern, Unit of Work and Testing

So I've been playing with re-engineering the data access in a project that I recently put into production.

I started reading about Repository and Unit of Work patterns and it got me intrigued. I'd never used TDD before but thought I might give it a shot.

What I'm working on isn't critical so it's more a hobby for me to get a better understanding.

I have got something working but want to see if I've missed the mark completely. Here's what I have... (I'll use Sln instead of the name of the solution for simplicity)

Sln.DataAccess
+ Entities
  + Person.cs (contains the model definition of a Person)
  + IIdentifiedObject.cs (just an interface demanding a (Guid)Id property)
+ Repositories
  + IRepository.cs[1]
+ IUnitOfWork.cs[2]

Sln.DataAccess.Memory
+ PersonRepository.cs[3]
+ Context.cs[4]
+ GenericRepository.cs[5]
+ UnitOfWork.cs[6]

Sln.DataAccess.Sql (I suppose this could be Sln.DataAccess.EF but anyway...)
+ PersonRepository.cs
+ Context.cs
+ GenericRepository.cs
+ UnitOfWork.cs

Sln.Test
+ Various unit tests.

The SQL Context/Repository/etc... are all essentially the same except that it access the database via Entity Framework instead of in-memory Lists.

The real question I am asking is whether I have missed the mark on the whole Repository/UnitOfWork patterns or if there are any suggestions anyone can give where I could improve on what I have.

Here are the source files.

There is no standard way to do a repository. It is meant to abstract something but something can be different things for different people. Some people have generic query methods, others only have specialized queries in the repo itself.

I'd think of use cases first and design the repository to work for those use cases. Design an address book application and think if your repository can provide the necessary functions in a convenient way.

OK so I achieved what I wanted.

See this project on Git that I created (it should be open) and it demonstrates exactly what I wanted.

The Sln.DataAccess assembly has absolutely zero references to how the data is actually stored, there are no classes in it, only interfaces that define the way objects can be accessed and the structure of those objects.

The actual means of persistence, (in-memory or database) are completely hidden from outside their respective assembly.

https://github.com/bmckenzie/projects

One thing I would like to fix is the Set<>() method in my in-memory Context class, take a look here: https://github.com/bmckenzie/projects/blob/development/Projects.DataAccess.Memory/Context.cs

I would rather avoid that if() {} and use some sort of a dictionary, if anyone has any suggestions?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM