Repository Pattern Best Practice

前端 未结 3 658
臣服心动
臣服心动 2021-01-30 05:23

So I\'m implementing the repository pattern in an application and came across two \"issues\" in my understanding of the pattern:

  1. Querying - I\'ve read responses

3条回答
  •  醉梦人生
    2021-01-30 06:14

    Regarding 1: As far as I can see it, it is not the IQuerable itself that is the problem being returned from a repository. The point of a repository is that it should look like an object that contains all your data. So you can ask the repository for the data. If you have more than one object needing the same data, the job of the repository is to cache the data, so the two clients of your repository will get the same instances - so if the one client changes a property, the other will see that, becuase they are pointing to the same instance.

    If the repository was actually the Linq-provider itself, then that would fit right in. But mostly people just let the Linq-to-sql provider's IQuerable pass right through, which in effect bypasses the responsibility of the repository. So the repository isn't a repository at all, at least according to my understanding and usage of the pattern.

    Regarding 2: Naturally it is more performance-effective to just return a single value from the database than the entire record. But using a repository pattern, you wouldn't be returning records at all, you would be returning business objects. So the application logic should not concern itself with fields, but with domain objects.

    But how more effective is it to return a single value compared to a complete domain object? You will probably not be able to measure the difference if your database schema is reasonably well defined.

    It is a lot more important to have clean, easy-to-understand code - instead of microscopic performance optimizations up front.

提交回复
热议问题