asp.net mvc page is not showing properties from associated objects

后端 未结 2 1559
悲哀的现实
悲哀的现实 2021-01-26 15:38

I have the following simple structure: Applicant Possition ApplicantPosition and ApplicantPositionHistory

The 3rd class has one reference with Applicant and one with Pos

2条回答
  •  迷失自我
    2021-01-26 15:48

    How is the Find method of your ApplicantPositionHistoryRepository implemented ? If it is something like

    return entities.ApplicantPosition.SingleOrDefault(expression)
    

    then you must enable eager loading like this :

    return entities.ApplicantPosition.Include("Applicant").SingleOrDefault(expression)
    

    Btw this is the reason why I personally dont like these "generic" repositories - there are always situations where you need eager load somethins, and also situations when it is just wasting of resources. In "non-generic" repository you would just create two methods

    GetApplicantPositionWithApplicant(int id)

    GetApplicantPosition(int id)

    and also your expression (which are in fact query logic if you think about it) stays in model (repository) instead of controller.

    EDIT (answering comments)

    About the "pain" of generic repositories : Generic repository is in general good idea only if you are building some really BIG application, where you want to separate things in more layers, typically - data-access layer (generic repositories), business layer (business logic, workflows, advanced validation etc.), and then control and presentation layer (controller+view in MVC). In this scenario, generic repositories only encapsulate trivial CRUD logic and are used only by business layer, not controllers.

    If you dont have some heavy stuff going on (non-trivial workflows, validation requiring external services etc.), then you have no real need for business layer, and you can "merge" it in data-access layer (or if you want, merge data-access into busines layer, they become one body one soul :)

    So, if you dont have some real business layer, you can only end up with some business logic in controller, because your generic repository is not really well suited for that. Non-generic repositories can contain your trivial business processing, and also you can implement custom CRUD for different scenarios - very good example is eager loading of things only when you know they will be needed).

    So decision of rewriting is really up to you and depends on your architecture and needs.

    About your exception :

    With SingleOrDefault, your variable history contains just one ApplicationPositionHistory object, and your view expects enumeration of ApplicationPositionHistory objects. Encapsulate this data retrieval in repository call with clear return value, you will prevent this type of errors.

提交回复
热议问题