DDD, Entity Framework, Aggregate Entity Behavior ( Person.AddEmail, etc) - entity-framework

Here's a simple example of a problem I'm running across that is not meshing with some of the ideas presented here and other places regarding DDD.
Say I have an ASP.NET MVC 3 site that creates/manipulates a person. The controllers access an application service layer (PersonService) which in turn uses the domain entities (EF 4 POCO) and the PersonRepository to make changes and persist them. I'm leaving out all interfaces here for simplicity. Person is the root in this case and for simplicity only has email addresses (also assume email is not immutable and can be updated).
Option 1:
Try to stick with [my understanding] of the basics of DDD where behavior directly related to the entity is implemented as part of the entity (Person implements AddEmail, ChangeEmail, etc). The only problem with this, with the exception of the Add* methods, is that the Person would need to know about the context or entity framework pieces (which would remove any persistence ignorance) or need to use a "service" or repository to mark the email as modified.
// Person Service
public class PersonService {
// constructor injection to get unit of work and person repository...
// ...methods to add/update a person
public EmailAddress AddEmailAddress(int personId, EmailAddress email)
{
Person p = personRepository.Find(p => p.Id == personId).First();
p.AddEmail(email);
uow.SaveChanges();
return email;
}
public EmailAddress ChangeEmailAddress(EmailAddress email)
{
Person p = personRepository.Find(p => p.Id == personId).First();
p.ChangeEmail(email);
// change state of email object here so it's updated in the next line???
// if not here, wouldn't the Person entity have to know about the context
// or use a service?
uow.SaveChanges();
return email;
}
}
// Person Repository
public class PersonRepository
{
// generic repository implementation
}
// Person Entity
public class Person
{
public string Name { get;set; }
public IEnumerable<EmailAddress> EmailAddresses { get;set; }
public void AddEmail(EmailAddress email)
{
this.EmailAddresses.Add(email);
}
public void ChangeEmail(EmailAddress email)
{
EmailAddress orig = this.EmailAddresses.First(e => e.Id == email.id);
// update properties on orig
// NOW WHAT? [this] knows nothing about the context in order to change state,
etc, or do anything to mark the email add updated
}
}
// Email
public class EmailAddress
{
public string Email { get;set; }
public bool IsPrimary { get;set; }
}
Option 2:
Let the person service use the repository to add/update the email address and don't implement the behavior on the person entity. This is much simpler in the case of many to many relationships (for example, address, where two tables need to be updated to complete the work) but the model then becomes 'anemic' being just a bunch of getters and setters.
// Person Service
public class PersonService {
// constructor injection to get unit of work and person repository...
// ...methods to add/update a person
public EmailAddress AddEmailAddress(int personId, EmailAddress email)
{
Person p = personRepository.Find(p => p.Id == personId).First();
personRepository.AddEmail(personId, email);
uow.SaveChanges();
return email;
}
public EmailAddress ChangeEmailAddress(EmailAddress email)
{
personRepository.ChangeEmail(email);
uow.SaveChanges();
return email;
}
}
// Person Repository
public class PersonRepository
{
// generic repository implementation
}
// Person Entity
public class Person
{
public string Name { get;set; }
public IEnumerable<EmailAddress> EmailAddresses { get;set; }
}
// Email
public class EmailAddress
{
public string Email { get;set; }
public bool IsPrimary { get;set; }
}
Anyway, any thoughts on this?
Thanks, Brian

Option 1 is the way to go.
Reasoning is simple - changing e-mail addresses is domain concern. I bet Your domain experts have said that they will need to change emails. That automatically marks email changing piece of logic as business logic which is supposed to live in domain model. Objects primarily are defined by their behavior and not data that they hold.
Also - think twice before You choose to use unit of work pattern and wrap around everything in services. Aggregate roots are supposed to draw transaction boundaries and services usually are useless if they just wrap repository and domain object calls.
I would have something like this:
public class Person{
public Email Email{get;private set;}
public void SpecifyEmail(Email email){
//some validation, if necessary
EnsureEmailCanBeChanged();
//applying state changes
Email=email;
//raising event, if necessary
Raise(new EmailChanged(this));
}
public class EmailChanged:Event<Person>{
public EmailChanged(Person p):base(p){}
}
}
public class Email{
public Email(string email){
//validations (e.g. email format)
Value=email;
}
//implicit to string, explicit from string conversions
}
public class PersonController{
public ActionResult SpecifyEmail(int person, string email){
_persons.Get(person).SpecifyEmail((Email)email);
return RedirectToAction("Person",new{person});
}
}
I'm using NHibernate - it's smart enough to figure out what has changed since Person was persisted last time. Hard to say how exactly entity framework handles this.

I'm an NH user and may not know all EF limitations but generally speaking, whatever the limitations of ORM, entities should be left as clean as possible. Service Layer is already coupled with Data Access so no harm's done.
And I believe EF4 should know how to track collection changes. If not, then the best way is to leave the adding/removing logic in your Person entity and persist in PersonService.
BTW, your EmailAddress isn't an entity here, no Id (just a typo I guess). And how do you link your EmailAddress to Person?

Related

best practice using method in a class

Suppose I have Employee class, should I put in the Employee class the add, delete, view, etc. methods? or should that class only for the getter/setter class?
which is better/acceptable/best practice?
Employee
-------------------
+int id (get/set)
+string name (get/set) (methods are called in another class)
Employee
-------------------
+int id (get/set)
+string name (get/set)
-add employee
-remove employee
This comes down to separation of concerns
When you are deciding these things, you need to use your intuition and think about it logically. What concerns an employee.
You have a class called Employee, then include in the Employee class everything that concerns an Employee. It doesn't make sense for an employee to be able to Add and Remove Employees to themselves. Maybe what you are looking for there is a class of Employees (plural) that will manage your employees ect ect ect.
But your Employee "will" have Name and Id and other things that concern it.
The goal here is to break up your concepts in to concrete real world concerns as much as possible, it makes it much easier to understand a design if you do
Assuming you have a database behind:
For similar purposes I have a base class for all entities that takes care of CRUD functionality and the ID. All entities inherit from this base class and take care of individual properties, like name, address, etc.
Also I have collections of all entities of the same type that manage the items in it.
Short Answer: Go with option 2
If you consider the separations of concerns, you should have an Employee to track the information of a single person and an Employee Repository for managing all of your employees. What makes up an record should be independent from how the record is stored/queried.
Employee class has information of employee, and the methods of employee. Looks like you are trying to maintain a collection of employees (assuming from add, delete employee requirement)
In that case add,delete,remove are not the responsibilities of employee class, rather the collection of employees.
Read on the OOP principles.
First 5 Principles of Object Oriented Design(S.O.L.I.D).
After Employee
public class Employee :ViewModelBase, IEditableObject
{
public int EmployeeID { get; set; }
public string FullName
{
get
{
return $"{this.Name} {this.Surname}";
}
}
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
OnPropertyChanged("Name");
}
}
}
After Create a Generics class with Repository For managment Add,Delete,Update etc...
public interface IRepository<T> where TEntity : class
{
IEnumerable<TEntity> GetUsers();
IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate);
TEntity GetById(int id);
void Save(TEntity model);
void Delete(int id);
}
And Employee Base implementation Repository
public Class EmployeeManager : Repository<Employee>
{
public IEnumerable<TEntity> GetUsers()
{
//your code
}
public IQueryable<TEntity> SearchFor(Expression<Func<TEntity, bool>> predicate)
{
//your code
}
public TEntity GetById(int id)
{
//your code
}
public void Save(TEntity model)
{
//your code
}
public void Delete(int id)
{
//your code
}
public void DeleteAll(Employee[] employees)
{
//your code
}
}
Unity Repository Best Practices
I think you should have all the tools you need in one class, have multiple constructors to help load only the info as needed.

WCF with Entity Framework Code First

I want to use EF behind my WCF service to fetch data and display it to the client. I need the following suggestions:
Do I need to have the same interface for all the views (e.g. students, teachers etc.) or do I need to have a different interface and service for every table (or view)
Do I need to generate the database calls within my service (.svc) or some other architecture is preferred?
public Student[] GetAllStudents()
{
//database generation code here
}
How can I use EF code-first approach to generate database. I know that for an MVC app, you need to set the initializer in Global.asax or in web.config but I am not sure how it's called in this case. My model looks like this:
[DataContract]
public class Student
{
[DataMember]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[DataMember]
public string Type { get; set; }
[DataMember]
public string Subject { get; set; }
[DataMember]
public string Description { get; set; }
}
What you really should do is break up your system in to more separate layers. Instead of having a WCF call that directly queries the database, create a "buisness logic" layer that translates the information that the WCF call provides you to what the EF call needs to know. This is called a N-Tier application
public class SchoolAPI : ISchoolAPI
{
private DataAccessLayer _dal = new DataAccessLayer();
public Student[] GetAllStudents()
{
return _dal.GetStudents(null, null);
}
public Student[] GetAllScienceStudents()
{
return _dal.GetStudents(null, DataAccessLayer.ScienceStudentType);
}
}
private class DataAccessLayer
{
public static readonly ScienceStudentType = //...
public Student[] GetStudents(string subject, string type)
{
using(var ctx = new SchoolContext())
{
IQueryable<Student> studentQuery = ctx.Students;
if(subject != null)
studentQuery = studentQuery.Where(s=>s.Subject == subject);
if(type != null)
studentQuery = studentQuery.Where(s=>s.Type == type);
return studentQuery.ToArray();
}
}
}
The caller of the WCF call does not need to know what the string ScienceStudentType is, all it cares about is that it gets the science students. By seperating the business logic from the database call the caller of your service no longer needs to know.
For EF it will initialize on the first time the framework goes out to "touch" the database and detects that it is not there if it is set up to do so. This is done in the constructor of SchoolContext but is getting a little too broad for this answer. I recommend finding a tutorial on EF and get it working in a simple test enviorment without WCF (maybe a simple console app that just calls GetStudents() then move in in to a WCF environment.

Handling dependent entities when deleting the principal with Entity Framework 5

Here's the situation in its most simplified form using the EF5 Code-First approach:
public abstract class EntityBase<PK>
{
public PK ID { get; set; }
}
public class Country : EntityBase<string>
{
public string Name { get; set; }
}
public class Address : EntityBase<int>
{
[Required]
public string CountryID { get; set; }
public Country Country { get; set; }
// ... other address properties ...
}
The one-to-many relationship between Address and Country is set up with no cascade-delete like so:
modelBuilder.Entity<Address>()
.HasRequired(a => a.Country)
.WithMany()
.HasForeignKey(a => a.CountryID)
.WillCascadeOnDelete(false);
Finally, I have a generic base repository class with CRUD methods that call SaveChanges on the underlying DbContext to commit data changes atomically. E.g.:
public class EFRepository<T, PK> : IRepository<T, PK> where T : EntityBase<PK>
{
//
// ... other methods ...
//
public virtual void Delete(T instance)
{
// ... trigger validations, write to log, etc...
_dbContext.Set<T>().Remove(instance);
try
{
_dbContext.SaveChanges();
}
catch(Exception ex)
{
// ... handle the error ...
}
}
}
Part 1:
Scenario:
var countryRepo = new EFRepository<Country>();
var country = countryRepo.Save(new Country() { ID="??", Name="Test Country" });
var addressRepo = new EFRepository<Address>();
var address = addressRepo.Save(new Address() { Country=country });
countryRepo.Delete(country);
This should fail due to the existence of a dependent Address. However, afterwards the address ends up with a null in CountryID, which is invalid because Address.CountryID is required, so subsequent SaveChanges calls throw a validation exception unless the address is detached.
I expected that when an object is deleted, EF5 will be smart enough to first check for any cascade-delete constraints like the one above and, failing to find any, then proceed to delete the data. But exactly the opposite seems to be the case.
Is this a normal behaviour or am I doing something wrong?
Part 2:
Following a failed SaveChanges call, some Addresses are now in an invalid state in my DbContext and need to be restored to their original values. Of course, I can always do so explicitly for each entity type (Country, State, Order, etc.) by creating specialized repository classes and overriding Delete, but it smells big time. I'd much rather write some general purpose code to gracefully recover related entities after a failed SaveChanges call.
It would require interrogating DbContext to get all relationships in which an entity (e.g. Country) is the principal, regardless of whether or not its class defines navigational properties to dependent entities.
E.g. Country has no Addresses property, so I need to somehow find in DbContext the definition of the one-to-many relationship between Country and Address and use it to restore all related Addresses to their original values.
Is this possible?
Answering my own question in Part 2:
Here is my approach to checking for related dependents when deleting an entity on the principal end of a many-to-one relationship and where dependents are NOT exposed as a navigation collection in the principal (e.g. class Address has a Country property, but class Country doesn't have an Addresses collection).
DbContext
Add the following method to the context class:
/// <summary>
/// Returns an array of entities tracked by the
/// context that satisfy the filter criteria.
/// </summary>
public DbEntityEntry[] GetTrackedEntities<T>(
Expression<Func<DbEntityEntry<T>, bool>> filterCriteria)
where T : class
{
var result = new List<DbEntityEntry>();
var doesItMatch = filterCriteria.Compile();
foreach (var entry in this.ChangeTracker.Entries<T>())
{
if (doesItMatch(entry))
result.Add(entry);
}
return result.ToArray();
}
Repositories
Create a repository for each class that has some dependencies, override the Delete method and use the new GetTrackedEntities<T> method to get all related dependents and either:
explicitly delete them if they are cascade-deletable in code
detach them from the context if they are cascade-deletable in the DB itself
throw an exception if they are NOT cascade-deletable.
Example of the latter case:
public class EFCountryRepository :
EFReadWriteRepository<Country, string>,
ICountryRepository
{
public override void Delete(Country instance)
{
// Allow the Country to be deleted only if there are no dependent entities
// currently in the context that are NOT cascade-deletable.
if (
// are there any Regions in the context that belong to this Country?
_dbContext.GetTrackedEntities<Region>(e =>
e.Entity.CountryID == instance.ID ||
e.Entity.Country == instance).Length > 0
||
// are there any Addresses in the context that belong to this Country?
_dbContext.GetTrackedEntities<Address>(e =>
e.Entity.CountryID == instance.ID ||
e.Entity.Country == instance).Length > 0
)
throw new Exception(String.Format(
"Country '{0}' is in use and cannot be deleted.", instance.ID));
base.Delete(instance);
}
// ... other methods ...
}
Example of a case where cascade-deleting will be done by the DB itself, so all we need to do is detach the dependents from the context:
public class EFOrderRepository :
EFReadWriteRepository<Order, string>,
IOrderRepository
{
public override void Delete(Order instance)
{
foreach (var orderItem in _dbContext.GetTrackedEntities<OrderItem>(e =>
e.Entity.OrderID == instance.ID ||
e.Entity.Order == instance))
{
_dbContext.Entry(orderItem).State = System.Data.EntityState.Detached;
}
base.Delete(instance);
}
// ... other methods ...
}
Hope someone will find this solution helpful.

What are the major limitations of EF4?

I am trying to decide on an ORM tool for my project, and I am thinking about EF4.
What are the major (if any) annoyances/limitations with this product? Also, does it support caching?
Thanks
This is a good place to start. Granted he's one of the main contributors of NHibernate so that particular post may seem a little bit biased, but there are some good links and arguments in the comments.
And looks like someone asked a very similar question on SO a few months back.
The inability to use private backing fields for lazy loading collections. For example take this class:
public class Account
{
private IList<Customer> _customers = new List<Customer>();
public IEnumerable<Customer> Customers
{
get { return _customers ; }
}
public void AddCustomer(Customer customer)
{
//Perform some biz rules
_customers.Add(customer)
}
}
Access to the customers collection is restricted by using an IEnumerable collection and having a AddCustomer / RemoveCustomer methods on the class. Typically you want to do some business checking before adding or removing a new customer.
The current version of EF requires lazy loading collection types to be ICollection (or any type that implements ICollection). So the above class now would look like:
public class Account
{
private IList<Customer> _customers = new List<Customer>();
public virtual ICollection<Customer> Customers
{
get { return _customers ; }
}
public void AddCustomer(Customer customer)
{
//Perform some biz rules
_customers.Add(customer)
}
}
Using a public ICollection Customers completely destroys good OO design principals as consumers could directly access by calling the Add Operation on ICollection.
Account acc = new Account();
acc.Customers.Add(new Customer()); //Bad code
The original intention of the domain class was to use the public add method:
Account acc = new Account();
acc.AddCustomer(new Customer());
NHibernate can handle this scenario through configuration. I would very much like to see this scenario supported in the EF.
Note however there is a workaround for the this limitation by declaring the the backing field as protected and map it through configuration:
public class Account
{
protected virtual ICollection<Customer> _customers = new Collection<Customer>();
public IEnumerable<Customer> Customers
{
get { return _customers ; }
}
public void AddCustomer(Customer customer)
{
//Perform some biz rules
_customers.Add(customer)
}
}
But this won't work if your application has a layered architecture (i.e your domain model is separated from EF configuration classes) because protected types are not accessible to external classes.
In order for this to work requires the EF classes to be in the same assembly as your domain models!
Lazing loading collections require a public or protected type that implements ICollection.

Does this Entity Repository Service example fit into Domain-Driven Design?

I would like to know if you find the following pattern meaningful in domain driven design.
The domain layer consists of model and repository. The application layer consists of services that handles queries from the user interface, or from controllers in the Model-View-Controller pattern.
Details of the structure:
// Assembly Model:
public class Phrase
{
public int PhraseId { get; private set; }
public string PhraseText { get; private set; }
public Phrase(string phraseText) { this.PhraseText = phraseText; }
public void SetId(int phraseId) { this.PhraseId = phraseId; }
}
// Assembly Repository (references assembly Model):
public interface IPhraseRepository
{
Phrase SavePhrase(Phrase phrase);
Phrase GetPhrase(int phraseId);
}
// Assembly Services (references assemblies Model and Repository):
public class PhraseService
{
private IPhraseRepository _phraseRepository;
public PhraseService(IPhraseRepository phraseRepository)
{
_phraseRepository = phraseRepository;
}
public Phrase SavePhrase(string phraseText)
{
Phrase phrase = _phraseRepository.SavePhrase(new Phrase(phraseText));
// doing other things like sending mail, logging, etc.
// ...
return Phrase;
}
}
Particularly, would it make sense to move the method into the Phrase entity class? In that case, how would that be called?
EDIT:
The example above has been modified after the answer from moffdub and the comment from Adeel Ansari. The changes are highlighted.
I would like to ask about the added IPhraseRepository.GetPhrase(phraseId) and how you would include that?
The repository should take in a Phrase, not a string. I'm also not sure why the SavePhrase method returns a Phrase. I tend to make such methods void methods.
Also, be wary of making every property in your domain model have public getters and setters. That can lead you to an anemic domain model.
Just some thoughts:
SetId(int phraseId) should not be public
Phrase could implement IPhrase (or IPhraseAggregate) which would not expose SetId(..)
SavePhrase(Phrase phrase) could (should?) return void if the reference to the phrase entity stays "valid" after saving:
public void SavePhrase(string phraseText)
{
Phrase phrase = new Phrase(phraseText); // NOTE: keep a reference to phrase
this._phraseRepository.SavePhrase(phrase); // NOTE: returns void
return phrase; // NOTE: assume the repository sets the phrase.PhraseId
}