2

I was wondering, should the entities have the capability to save changes to the context? Or have business logic that relates to that particular entity? For example:

ActionResult ResetPassword(UserViewModel viewModel)
{
   var user = userCollection.GetUser(viewModel.Username);
   user.ResetPassword();
}

where:

class User : Entity
{
      public string Password{ get; set; }

      public ResetPassword()
      {
           Password = ""
           context.SaveChanges();
      }
}

I find this a bit weird since the entity would have a reference to the context. I am not sure whether this would work either - or whether this is recommended. But I want to work on a domain where I do not have to worry about saving changes, at a higher level etc. How can I accomplish this?

Thanks!

Update

I have updated my example - hope its a bit clearer now :)

Karan
  • 14,824
  • 24
  • 91
  • 157

3 Answers3

2

According to Domain-Driven Design domain objects should have behavior.

You should definately read this book:

enter image description here

Steven
  • 166,672
  • 24
  • 332
  • 435
  • 1
    in order to achieve domain-driven behaviour, each entity would have to have a reference to the context, as stated in the question. This seems to be fighting against the mvc .net framework. Have you attempted to do this? – Karan Oct 10 '12 at 09:16
1

I would keep my Entities as POCO's(Plain Old Class Objects, classes with only properties) and have a Repositary do methods like Insert / Update.

I can keep my Entities in a separate class library and use it in different places ( even in a different project), with a different Repository implementation.

In this Tutorial It is nicely explained, how to do a Repositary & Unit Of Work Patterns on an MVC project which uses Entity Framework

Shyju
  • 214,206
  • 104
  • 411
  • 497
  • 2
    That is interesting. See, I had a different idea. I thought the domain objects should have behaviour as @Steven mentioned. And I thought the models were effectively the entities - such as User. Perhaps a better example would be - whether a user can reset a password. I would have thought it would be the User's responsibility rather than a Repository's responsibility. What do you think Shyju / Steve? – Karan Aug 17 '12 at 14:28
1

You may want to consider the UnitOfWork pattern between your controller and your entities.

http://martinfowler.com/eaaCatalog/unitOfWork.html

podiluska
  • 50,950
  • 7
  • 98
  • 104