Tagged: entity framework Toggle Comment Threads | Keyboard Shortcuts

  • danielsaidi 12:52 pm on November 16, 2011 Permalink | Reply
    Tags: entity framework, repository, service   

    Controllers, repositories, services – where do I put the logic? 

    I could use some advice regarding a project that I am currently working on. The project is a web site, where members can join various groups (did I hear “Facebook already has that”?) and do stuff depending on what groups they belong to.

    Let’s ignore all other entities and focus on the Member and Group entities.

    I have a repository interface/protocol for each entity. The main repository’s sole responsibility is to communicate with Entity Framework (I also have other implementations of each repository interface, e.g. fake repositories that just create fake data, cache decorators etc.).

    I then have service classes (I know, I know…bad name) for more sophisticated functionality. The controller classes of my web site then use the various service classes to do stuff. Service classes can talk to each other, repositories can not.

    This architecture can be illustrated (quite simplified) as such:

    A simplified architectural view

    A simplified view of the architecture

    Now, here is my dilemma…where do I put additional logic?

    Say, for instance, that I want to be able to find all members that are in the same groups as a certain member. I could then:

    • Add a GetGroupFriends method to the Member entity. The method could then iterate over all the groups that a member is a member of (which would require stepping through Member -> GroupMember -> Group), and return a distinct list of members that are members of the same group.
    • Add a GetGroupFriendsForMember method to the MemberService and do mostly the same thing as above, but working with a repository to retrieve data instead of drilling down the member object.
    • Add a GetGroupFriendsForMember method to the GroupService and do mostly the same thing as above, but working with the repository to retrieve data instead of drilling down the member object.
    • Add a GetGroupFriends method to the Member entity and a GetGroupFriendsForMember method to one of the service classes, and make the service call the entity method.
    There are naturally some pros and cons of both methods:
    • Placing the method in the Member entity is simple, and using the method is also quite straightforward, but…
    • …it will also cause coupling. Also, the Member entity is not abstract, which means that we cannot mock it that easily (although some mocking frameworks support this)
    • Placing the method in a service is also simple and nice approach, especially since each service is abstract, but…
    • …which service should then own the logic? I would go for the group service, but I do not really know.
    I started of with placing the methods in the entities, trying to be a good OO programmer, but the responsibilities of the entities then grew and grew. I abandoned that ship.
    Now, I have all my relation- (is X a member of Y, does X know Z) and permission- (can X edit Y, can X invite Y to Z) -related logic in the various services. It’s quite nice, but in some cases, I find that the services have to evaluate data in really non-optimal ways.
    There are probably tons of  various solutions to this problem of mine…I would just really like to discuss this. If you have found a way that works for you, please share it with me 🙂
    • Henrik 2:13 pm on November 16, 2011 Permalink | Reply

      Maybe not an answer. But I try to think in real life scenarios. But i’ts very hard. Sometimes it’s hard to translate an abstraction to real life. But most often the problems are contextual. Like, who desides if you’re a member of a group? You? The group? A concensus? Someone else? Well, it depends on the context. If you are a member of a band, it’s quite obvious – either you play (or sing) in the band or you’re not. If you’re a unoin member, it’s also quite obvious (you pay the uinion fee and are listed – and the union desides if you’re a member or not). Case closed. But what about a friends group? You maybe think you are a member (or want to be), but your friends might not (if you know what I mean 🙂

      The same thing goes for validation. Who desides if you’re allowed to buy alcoholics? You or the person behind the desk? Well, actually the law says you can or not, but maybe that’s a to big abstraction?

      In your code you have some kind of GroupService. What’s that in the real life? Do you go to the big old group service station and ask: “I’m I a member of this band?” But on the other hand, you could call the union info desk and ask them for all members in your company (e.g.) That’s kind of a member service…

      And what is a Member? If you look from your own perspective (“I’m a member”) it might be one thing, for others it may mean something else (“He’s that member”).

      I’m kind of talking DDD here. And maybe that’s a to big step in your case. But it’s very interesting thoughts though 🙂

      Think Unix! Build small objects that do one thing and does it very well! That way they are easy to replace if they start to smell bad (think Dan North 🙂 A big “MemberService” may grow up to be a dragon, and then it will be hard to replace… or maybe not? Embrace uncertainty! Always know you *may* write crappy code, just don’t get emotionally attached to it and prepare for it to be replaced or removed.

      And don’t forget “Tell, don’t ask”!

      • Henrik 2:18 pm on November 16, 2011 Permalink | Reply

        Lots of types there 🙂 union, uinion, unoin,uoinuoinuoniunoinu? “I’m I a”?, “Am I a”? Don’t know…
        I should have prepared the comment to be removed or replaced.

        • danielsaidi 8:13 pm on November 16, 2011 Permalink

          I think your comment was great. It will live on forever.

      • danielsaidi 8:11 pm on November 16, 2011 Permalink | Reply

        Great stuff, Henrik. I will reply to your comments separately.

        I think your real-life example is really good, especially that “go to the big old group service station” part 🙂 However, keep i mind that my example above is really simplified. There are various kinds of members. First, there is the native Membership account (MembershipUser), which is one kind of member…or rather, an account. Then, we have a web site member, or the domain’s definition of a member. That is the entity that represents the web site user, which has connections to items, group memberships etc. We also have a group member. So, there ARE distinctions.

        I think that you would agree that my solution is populated to the brink of explosion with small classes that do “one” thing. I also think that you can go too far in trying to achieve SRP. IMO, placing related functionality in one class that grows a bit is no biggie, IF you have unit tests, abstractions etc. that makes refactoring easy when the need arises.

        However, in this particular case, when looking at the GroupService interface, I think that there is actually time for some refactoring. It is responsible for group management, group member management and group relations.

        Still, my question was more general…these two entities were just an example. Look at my question in this, new light:

        “I have entity A and entity B”.
        Each have basic methods, derived properties etc. that are directly related to the data of the entities.
        More complex entity operations are moved to an abstract service class per service.
        Where should methods that handle relations between the two entities go?

        I know where this is going…that I need more classes that do less stuff. Thank god that my code is so great (smell the irony) that these changes are cheap and easy to perform.

        I have only answered your first comment, and am already enlightened beyond what I first thought was possible. Man, you are a good listener! 🙂

    • Mattias Lind 2:22 pm on November 16, 2011 Permalink | Reply

      What you need is a GroupMemberService. Do I need to say more. 😉

    • Henrik 2:42 pm on November 16, 2011 Permalink | Reply

      If you start thinking “Where do I put additional logic?” It should be a signal, a trigger that say “hey, something isn’t right here!” You shouldn’t have to ask that question, right? Or am I wrong?

      • danielsaidi 8:24 pm on November 16, 2011 Permalink | Reply

        I do not agree at all. Let’s go for the Member and Group example once more.

        We have a Member entity and a Group entity.
        We have a MemberRepository (IMemberRepository) and a GroupRepository (IGroupRepository) that are responsible for data management.
        We have a MemberService (IMemberService) and a GroupService(IGroupService) that are responsible for basic entity handling, like get, delete, search etc.

        Now, where do we put relational logic? Forget about the “additional” word. Where do we put logic that maybe do not fit these services, that only handle a separate entity.

        In some cases, I do not think that adding them to one of these services (e.g. an AddGroupMember method in the GroupService class) is terribly wrong. If it is just one method, I would go as far as to say that adding it to one of these service classes is BETTER than to introduce another class.

        IMO, you CAN go too far with SRP.

        So no, I do not think that something is wrong. It is just a situation where we ask ourselves a question where we want a certain kind of functionality to go…

        ..but I can be wrong as well. That’s why I love having these kinds of discussions.

        • Jon 8:39 pm on November 16, 2011 Permalink

          Is your application a Member-something application or a group-something application? Or do you think it is booth? Does answering that question make you think differently about where to place the method?

    • Mattias Sundberg 2:53 pm on November 16, 2011 Permalink | Reply

      I wouldn’t put the logic in either of them without knowing the purpose of the functionality. As PHP-programmer I would put such logic in a static class with misc utilities becuase it doesn’t correspond with the data objects. Although one way to go would be to have all groups a member belongs to as properties to the member-object which you then could iterate. And groups would have all members as properties. Sure, fair bit of recursion but iteration could be done extremely fast.
      Or why not place your ACL-logic in the database?

      Either way, you .NET-guys complicate things too much haha

      • danielsaidi 8:32 pm on November 16, 2011 Permalink | Reply

        I would never place such login in a static utility class. Static classes are convenient, sure, but the convenience comes with a too high price to pay. Coupling, lack of abstractions etc…which will make such a simple thing as unit testing your code a nightmare (or even not applicable).

        At the very least, I would place each method that I find no other room for in a separate interface. The class that then implements the interface can then be replaced with any other implementation or mock…which makes such a simple thing as unit testing…simple.

        Come on, you (we…I apply the exact same method when writing PHP code) have interfaces in PHP as well. There is absolutely no need to go for those monster utility classes 😉

        • Mattias Sundberg 10:05 am on November 18, 2011 Permalink

          I started to write a comment that almost became a novel but I scrapped it 🙂
          Anyway, what I’m trying to say is that the purpose of your application should dictate which route you take. I’ve seen to many projects become monstrous just because designers view their code in a philosphical way rather than being pragmatic.
          When I design a framework or system I always start with “whichdirection might the client take in the future with this”.
          Abstraction isn’t always needed, coupling isn’t always a problem, unit testing is a waste of time in 90% of all web applications in my opinion 😉

          And in your particular project my gut feeling is that you are using methods that are a bit overkill. I don’t say it’s wrong but I don’t see the point (with regards of not knowing the purpose of the application) 🙂

        • danielsaidi 11:56 am on November 19, 2011 Permalink

          Ha ha ha, yeah some of my comments became too long as well…this one included 🙂

          I agree with you to some extent, but in my case…having three separate classes that deal with one thing instead of one huge one that deal with all…well, I prefer the small ones. Also, making them non-static and interface-based come at a(lmost) zero cost and does not IMO introduce a dramatic amount of extra complexity.

          Instead, being able to talk about that classes use other components that can do something, no matter how, is something I would not throw away for the world.

          But I really agree with “abstraction isn’t always needed, coupling isn’t always a problem”, I really do. I just think that designing the system in a way that tackles these potential(!) problems is not that much more complex than just going for a simple, unflexible approach.

          It’s like placing all your language strings into one file instead of spreading them all around your code, even though you will not need localization – when you need to change or re-use a translation, you know exactly where to look. It’s a great convenience.

          Things take time for me at this point, since I am rather new to this thinking and interesting questions pop up all the time. Just like with everything else (TDD for instance), once I have refined this way of working, I am sure that it will take less time, be more fund and result in better systems.

          And unit tests…would not throw away them either, and do not agree about your 90% rate 😉 Sure, I tend to write too many tests, like testing my MVC controllers…which often tend to make me spend time at adjusting tests in a part of the system that go through the greatest amount of changes. However, having done this several times, I can now make the choice to NOT write tests for all parts of the controllers…at least not until the first sharp version is shipped.

          So, where the tests are good, they are invaluable IMO…especially in teams with several developers, and especially when using a build server, like TFS, that can continously build and test code that is checked in.

          But, as you say, we probably build quite different systems and benefit from different things. You like your way of working, I love (or am beginning to) my way. Win-win situation? 🙂

          And there, another novel 😀

    • Jon 8:14 pm on November 16, 2011 Permalink | Reply

      This is a very interesting problem and as you point out there is of course no “right answer”. I spent a lot of time thinking about these issues the past year or so.

      Jimmy Bogard wrote a bunch of great blog posts about Strengthening your domain http://lostechies.com/jimmybogard/2010/02/04/strengthening-your-domain-a-primer/
      At the end he discusses weather to inject services into the domain objects http://lostechies.com/jimmybogard/2010/04/14/injecting-services-into-entities/
      His conclusion is that it is not worth it from a testing and simplicity point of view. I tend to agree with him.

      My logic often ended up in somewhat bloated services. But there is no one stopping you from having more services that are more specialized if they get hairy.

      I am moving towards an even more simplistic view on these problems. If we don’t have a real domain, must we really have all this infrastructure, or/mappers, services, repositories and so on for displaying some data on a web page and occasionally update it?

      Perhaps we can make it smaller, tighter and more understandable without loosing testability (scalabillity is another interesting discussion but perhaps in another post)

      What I am suggesting is looking at how the cqrs guys handle their view models: just get the freaking data with a sql query and show it. Perhaps in a nice little dto. Let the “smart” part of the application use an object model if it is needed.

      Does it sound wierd?

      • danielsaidi 8:43 pm on November 16, 2011 Permalink | Reply

        Great comment, Jon…and thank you for the links. I will check them out!

        I think the “no right answer” part is what makes the binary programmer brain go into a spin. If there is no correct answer, then we work ourselves to the bones to find the BEST solution. If you cannot be correct, you can at least choose the BEST option available. At least, that fits me.

        If I would have built the same solution in PHP, using my own framework, the solution would have been SO much simpler. Sure, not as flexible, but simple. In this project, I want to throw up when I see all these classes and interfaces, although I know (or at least, I am 99% sure) that I have done things “by the book”.

        It is like my wife said – in projects where “doing it right” or “doing it by the book” is a measure of success, failing to deliver is more likely to be the outcome.

        In the end, I am disgusted by the amount of classes and interfaces this fairly simple web site has ended up requiring…but, at the same time. I understand each class (although some services are rather big) and find it really easy to work in the solution. So, I would say that I’d choose the current architecture before anything I’ve worked with before, any given day.

        Still, I think CQRS will probably throw me off my feet when I start looking at it.

        • Jon 8:50 pm on November 16, 2011 Permalink

          The CQRS stuff made me think a lot. Not that it fits in many projects I have been working on and it is definitely not a silver bullet but it has some very appealing back to the basics to it that can be applied in many other scenarios.

        • Henrik 10:21 pm on November 16, 2011 Permalink

          I really like this!
          If it’s simple but not flexible doesn’t that make it right to? As long as you are prepared to throw things away there’s nothing wrong in building just the right thing (and ignore the flexibility). And to be honest, how often do we need the flexbility we have built? I think we mostly build it “by the book” because it is *fun*. Nothing else. And sure, there’s nothing wrong with that either!

          How I love this: if ‘doing it by the book” is a measure of success, failing to deliver is more likely to be the outcome.’ So true! 🙂 I’m gonna steel that and twitter it.

          But, is it “by the book” to have a zillion interfaces and classes? When I think of unix I think of all the little “tools” you have that does just one thing, But I don’t care *where* they are, I just have them and they do the work. I don’t really know where I’m going here… Trying to think of how to do it in .NET… have a zillion small projects instead? Probably not, maybe .NET isn’t the best tool for these things? To be honest I don’t think OOP is the best thing. We should move to Message-Oriented Programming http://c2.com/cgi/wiki?MessageOrientedProgramming. It’s not the objects that are interesting, it’s the communication between them. And that corrolates very well with the real life! A stone is very boring (it doesn’t communicate very well) but you can sit and watch a human being for hours. But both are objects!

        • danielsaidi 11:03 pm on November 16, 2011 Permalink

          I definitely agree with MOP. Although I have not applied it in any project, and it surely has a lot of drawbacks bundled with all the goodness it brings, it “feels” right.

    • Jon 8:22 pm on November 16, 2011 Permalink | Reply

      Another thing I have been thinking about:
      Why do we need repositories? I have been using them for quite some time because “every one is doing it” But when I think about *why* it boils down to abstracting your data source. Plus the testability of course.

      But when we use EF och NH we have the datacontext and the session and they are essentially a generic repository that can be mocked away. All we are doing is adding another layer of complexity on top.

      The only real reason I can think of is to swap the data source for something completely different. In my time as a developer I have done this exactly twice. The benefit I gained from the repositories was minor. And if you want to have it you would perhaps be better of just wrapping it in an ISession the way Rob Conery does in the asp.net MVC series.

      • danielsaidi 8:51 pm on November 16, 2011 Permalink | Reply

        I remember having this discussion two years ago, when I did not see the point and you tried to make my slow mind understand why they are good to have.

        Now, I think that repositories are an absolute must-have.

        First of all, if you did not have the repositories (which in my case more or less always contains bool Delete, bool Save, T Get and IQueryable GetAll) you would have to place the CRUD logic in your services, which I find a bit messy.

        Second, by using the repository pattern, I have one way of working with entities, no matter which solution I work in. Sure, I can also switch between fake data, real data, no data etc, but in the end, letting a repository handle data operations in each solution makes me work faster.

        I have a nice R# Live Template that helps me generate all required repo/service interfaces and classes, so time invested for me to have a repo is ~ 0 (maybe a little more if my repo should behave differently in some case)….do not tell anyone that I use R# live templates this way (although I accidentaly told Hadi once…big mistake).

        But once again, there is no right answer, and I may very well be (read: I am most likely) wrong. I usually am 🙂

        • Jon 8:57 pm on November 16, 2011 Permalink

          Valid points – we are back to the dreaded “it depends” =P

    • danielsaidi 9:05 pm on November 16, 2011 Permalink | Reply

      Ha ha ha, yes…the end to which all roads lead.

    • Niklas 6:13 am on November 17, 2011 Permalink | Reply

      When something feels awkward it usually means that something is missing. Is there maybe some implicit concept that needs to be made explicit? I don´t really get what a ‘Member’ is either. Could it be that instead, some User has a Membership to a Group? And that the Membership knows these things you are trying to place somewhere.

      • danielsaidi 7:36 am on November 17, 2011 Permalink | Reply

        As I wrote to Henrik, “additional” was a bad word to use. Rather, if I have two entities and one dedicated service each, where do I put stuff that, maybe, handles relational functionaltiy between the two entities. But yes, I agree…something WAS missing. For the group membership-related functionality, I have not extracted those 7 or so methods into a separate class. Privilege-related methods have been given one separate class per entity as well. It’s rather hard to describe without code examples, but now, all feels natural.

        But, as I also wrote earlier, I think that placing some piece of functionality in the “wrong” class is no biggie. To have two classes, where a MemberIsGroupMember methods ends up in the group service is not THAT bad…but, if the number of membership-related methods grow, then you should probably consider extracting them into a separate component.

        • Niklas 5:53 pm on November 17, 2011 Permalink

          In general, if a method is just some query to your datalayer, I think it should be put in the repository. But if the method contains some business logic important to your model, then it should probably go into the entity.

          If talking DDD, which your vocabulary suggests.

        • danielsaidi 6:34 pm on November 17, 2011 Permalink

          But placing it in the entity is not good if it is not just logic that can be directly derived from your entity data, e.g. CanBeProcessed for an Order, which then checks several properties to see if the Order is properly setup.

          I would not put too much or too complex login in the entity…but I may be totally wrong.

    • danielsaidi 11:18 pm on November 17, 2011 Permalink | Reply

      Guys, I just want to thank you SO much for this discussion (I am NOT putting an end to it, I would love for it to continue). After having it, I was so inspired that I sat with my code for a couple of hours, looking at it in new eyes. The changes I made are really small (moving a couple of methods to new classes), but it made the whole system so much more obvious.

      It is like Niklas wrote “when something feels awkward it usually means that something is missing”. And it did! Splitting my not that large, but too large nontheless, services into several ones made the design better, simplified testing etc. etc.

      Thanks once again!

    • Per Tronelius 11:47 pm on November 17, 2011 Permalink | Reply

      Lots of comments…
      But I must say that I agree mostly with Henrik. Let your Entitys be your “real life objects”, and let them contain Business logic… that’s why we have them, If they don’t contain logic, you should start calling them DTO:S. Your Order object a few comments up seems like an DTO with an extra get-property, nothing else.

      Use Repositories to separate your current choice of datapersistance from your Entities, making them POCO. Use repositories for persistance and effective loading of objects/graphs of objects, and use the Entities for your logic, and think of them in “real world terms” and you will find where to put the logic…

      I haven’t seen your code, but sometimes it sound like your in a “class-creating-race” and tries to separate everything into tiny individual pieces. Try for a change to create code in more of a B.B King style… with very few notes (classes) played well, rather then to code like your in a yngwie Malmsteen solo.

      • danielsaidi 12:08 am on November 18, 2011 Permalink | Reply

        Well, I now have a structure that I really think is both easy to understand and maintain, so I will go for it…until I realize that I am entirely wrong.

        So, to give you a clue about how my code works, here goes.

        My repositories work just like you described. My entities are POCOs. I can then switch out EF4 whenever I want to. For instance, I quickly made Swaplet store interested visitors in a text file instead of in the database (of which I had none live at the time).

        For the examples below, a Member is an object that is coupled with a Membership account. It contains user information, handles relations with other entities etc.

        Sorry for the terrible formatting of the code below.

        I extend my POCO entities with partial classes and metadata classes, which makes the partial Item class look something like this:

        public partial class Item
        public string ImageUrl { get; set; }

        public bool IsLentOut
        get { return LentToMemberId != null; }

        public bool MemberHasLentItem(Member member)
        return LentToMemberId == member.Id;

        public bool MemberIsOwner(Member member)
        return OwnerMemberId == member.Id;

        public class ItemMetaData
        [Required, MinLength(1)]
        public string Name { get; set; }

        A common repo can look something like this:

        public interface IMemberRepository
        void Delete(Member obj);
        Member Get(Guid id);
        IQueryable GetAll();
        Member Save(Member obj);

        I have a basic service for each entity, which lets the system manage entities of that kind in various ways. For instance:

        public interface IMemberService
        void DeleteMember(Member member);
        IQueryable GetAllMembers();
        Member GetMember(Guid memberId);
        Member GetMemberByFacebookId(int facebookId);
        Member GetMemberByUserName(string userName);
        Member SaveMember(Member member);

        After yesterdays discussions, I separated some privilege logic from these services into separate ones. For instance, these methods used to exist in the IGroupService:

        public interface IGroupPrivilegesService
        bool MemberCanEditGroup(Member member, Group group);
        bool MemberCanInviteToGroup(Member member, Group group);
        bool MemberCanLeaveGroup(Member member, Group group);
        bool MemberIsGroupAdmin(Member member, Group group);

        I do not think that this is a too complex model. In fact, I think it is really, really nice. Basic logic that directly relates to available entity data (OBS without drilling down into any relational data) ends up in the partial entity class. Basic entity handling logic ends up in a service with the same name as the entity (sure, the name sould probably change), and login that do not fit into this model ends up in separate classes.

        The only thing I am not happy about here is the naming of the classes, but hey, that’s really just semantics. If that is the convention of my code, and I stick to it all the way, I think that justifies naming the basic service classes XService. Naming conventions is really not the biggest part of this discussion.


    • Henrik 4:42 pm on November 18, 2011 Permalink | Reply

      I’m quoting a collegue. You’re facing a classic problem when using an anemic model.
      I reckon you have a lot of service classes that validates and work with your entities from the outside?
      “Entities Have an Identity and a Life”: http://msdn.microsoft.com/en-us/magazine/dd419654.aspx#id0090053

      • danielsaidi 12:07 pm on November 19, 2011 Permalink | Reply

        But now, after Niklas comment “…womething is probably missing” I really do not see a problem with my way of developing now. I really like the design of my system now, although I use IoC, DI etc…which some find being overkill. I rather find it being a great convenience, once one get use to this way of thinking.

        But looking at the link you sent me, I do not disagree that entities should have logic. The question is, should they have relational logic? Should everything I can do with an entity, like relational stuff (find all group members for a group) also go there? What is the responsibility of the entity…to handle everything one can want to do with it? I disagree…but I agree that one can probably put more logic in the entities than I tend to do.

        • Henrik 10:43 pm on November 20, 2011 Permalink

          You are absolutely right. When it comes to the relational logic that’s where the service classes comes in. But you *only* use them for those cases, then they become very thin and isolated. For the rest, let entities have logic. But if you are happy I’m happy! 🙂 If you are happy and think everything is great, then you are home! Nothing else matters 🙂

        • danielsaidi 11:08 pm on November 20, 2011 Permalink

          Another danger I see with letting EF(!) entities be responsible for a lot of their logic is that it may encourage placing entity navigational code into them, for instance:

          public partial class Member {
          public bool HasItems { get { return Items.Count() > 0; } }

          This is a very trivial example, but I think it is good to demonstrate what I think (obs, I am not sure at all) may be dangerous.

          Member is an EF entity with an association to the Item entity, which generates the navigation property Items.

          However, if I was to choose to persist items in another way, outside of the EF context, then this way of retrieving items would be at a loss, since my items would not be stored in the same database as members.

          Still, Jon sent me this Dan North lecture:

          Consider this project to be my second project 🙂 I want to do stuff right, and think I am on my way, but in this strife, I also often go too far, which makes the project take a lot longer time than if I would have just created it with, say, Wigbi.

          So, I am really not that happy 😉 I am more happy to be able to discuss these things with you guys than how my project is finally coming along. Luckily, doing stuff by the book was one of the major goals for me (which I can allow myself since it is a hobby project).

          Let’s just hope that failure to deliver will not be the outcome 😉

        • danielsaidi 11:09 pm on November 20, 2011 Permalink

          Oh, and another reflection. EF aims at making it easy for you to quickly get something up and running, so maybe trying to optimize for using is is, well…maybe it should come later. Maybe drilling down the entity relations would be just fine for now.

          We’ll see how I do things in my next project 😉

  • danielsaidi 11:37 am on July 5, 2010 Permalink | Reply
    Tags: , constraintexception, , entity framework, ,   

    ConstraintException thrown when posting empty data for non-nullable properties 

    I am currently working with model validation, using an EF4 entity model, DataAnnotations and partial classes with MetadataType connections.

    In my model, I have an Employee entity for which some of properties are non-nullable. I have also created a partial class and a meta data class for model validation, as is described in this blog post.

    This works great. The Employee class is validated properly, with minimum effort. My entities are validated with standard validation attributes as well as custom ones. Lovely.

    However, the application crashes when I post empty text input elements in my Create/Edit views. A ConstraintException is thrown before my view controller actions are executed, which means that I cannot act on the constraint exception within my action.

    The exception is caused by the fact that empty posted data will cause the corresponding model properties to be set to null, which conflicts with the non-nullable properties in the entity model.

    However, since I have custom model validation classes in which I add Required attributes to mandatory properties, I do not need the non-nullable attributes in my entity model. As such, I set the nullable property to (None)…and the ConstraintException is history!

    • Thomas 3:29 pm on September 24, 2010 Permalink | Reply

      Surely this is the incorrect approach, as it means you have no constraints set at the root database level. Which seems wrong.

      There is actually no problem with a constraint exception being thrown, that’s exactly what is supposed to happen.

      • danielsaidi 11:57 am on October 4, 2010 Permalink | Reply

        Hi Thomas! Thank you for your input, you are absolutely right. I have updated the post according to your feedback.

    • temStetLody 10:05 pm on June 21, 2011 Permalink | Reply

      Hello all! I like this forum, i found numberless interesting people on this forum.!!!

      Large Community, good all!

    • Hector 4:47 pm on June 3, 2012 Permalink | Reply

      I know, I know, it has been almost two years since this was posted.
      But just in case someone else is looking here for a solution, I just managed to get around.
      You may use the “DisplayFormat” DataAnnotation in order to override the default behavior (empty posted data causes corresponding model properties set to null), like this:

      [DisplayFormat(ConvertEmptyStringToNull = false)]

      Add the annotation for each non-nulleable attribute of the model. Then, EntityException is gone, and validation still works.

      Best regards.

      • danielsaidi 4:53 pm on June 3, 2012 Permalink | Reply

        Yeah, the post is rather old…and invalid. I should update it, but…well 😉

        Thank you so much for your comment!

  • danielsaidi 1:03 am on July 5, 2010 Permalink | Reply
    Tags: callwithmodelvalidation, , entity framework, , modelstate, ,   

    DataAnnotations and MetadataType fails in unit tests 

    This post describes how to solve the problem that model validation will not work for ASP.NET MVC2 (.NET 4.0) when testing a model that uses DataAnnotations and MetadataType to describe for its validation.

    First of all, ModelState.IsValid is always true, since the functionality that sets it to false if the model is invalid is never executed during the test cycle. This will cause your controllers to behave incorrectly during your tests.

    Second, MetadataType binding is ignored during the test cycle as well. This will cause the validation within it to be ignored as well, which in turn will cause the model to be valid although an object is invalid.

    My situation

    I am currently writing tests for a Create method in one of my controllers. I use NUnit as test framework. I have an EF4 Entity Model, in which I have a couple of entities. For instance, I have an Employee entity with FirstName, LastName and Ssn properties.

    To enable model validation, I create a partial Employee class in the same namespace as the EF4 entity model, then create a MetadataType class, which handles validation for the class. This approach is fully described in this blog post.

    In my EmployeeController, I have a Create method that takes an employee and tries to save it. If ModelState.IsValid is false, the controller returns the Create view again and displays the errors. If the model is valid, however, I create the employee and return the employee list.

    Easy enough. Well, when I started to write tests, I realized that ModelState.IsValid is always true, even if I provide the method with an invalid employee. Turns out that model validation is not triggered by the unit test.

    Trigger model validation within a test

    This blog post describes the ModelState.IsValid problem and provides a slick solution – the CallWithModelValidation Controller extension method.

    I added this extension method to my MVC2 project and used it instead of calling Create, as such:

       var result = controller.Create(new Employee());
       var result = controller.CallWithModelValidation(c => c.Create(new Employee()), new Employee());

    And sure enough, this causes the test to trigger model validation. The only problem is that the model validation does not catch any errors within the model, even if the model is invalid.

    After some fiddling, I noticed that this error only occurs for partial objects that uses MetadataType to specify model validation. A class that describes its validation attributes directly is validated correctly.

    Turns out that the MetadataType class is ignored within test context. Thus, the model is always considered to be valid.

    Register MetadataType connections before testing

    This blog post describes the MetadataType problem and provides a slick solution – the InstallForThisAssembly method.

    This method must be placed within the same assembly as the model, in other words not the test project. I placed it in a ControllerExtensions class file and call it at the beginning of CallWithModelValidation. This works, but will not work if you move the extension to another project.

    Run it before your tests, and everything will work “as it should”.

    Hope this helps.

  • danielsaidi 11:36 am on July 1, 2010 Permalink | Reply
    Tags: entity framework, poco   

    Entity Framework 4 and POCO 

    I am currently playing around with EF4 and its POCO support. The Entity Model approach is really great, and it suits me well, since I am used to generate a database from an object model.

    A good thing about having an entity model is that it is part of your solution in a way than the database is not. So, if you do not have access to the central database (if any), you just have to right-click the entity model, generate the database and you’re good to go.

    This blog (although in Swedish) is a great introduction to POCO.

Compose new post
Next post/Next comment
Previous post/Previous comment
Show/Hide comments
Go to top
Go to login
Show/Hide help
shift + esc