I think I ve hit that "paralysis by analysis" state. I have an MVC app, using EF as an ORM. So I m trying to decide on the best data access pattern, and so far I m thinking putting all data access logic into controllers is the way to go.. but it kinda doesn t sound right. Another option is creating an external repository, handling data interactions. Here s my pros/cons:
如果把数据输入控制器,我最后将采用这样的编码:
using (DbContext db = new DbContext())
{
User user = db.Users.Where(x=>x.Name == "Bob").Single();
user.Address.Street = "some st";
db.SaveChanges();
}
So with this, I get full benefits of lazy loading, I close connection right after I m done, I m flexible on where clause - all the niceties. The con - I m mixing a bunch of stuff in a single method - data checking, data access, UI interactions.
With Repository, I m externalizing data access, and in theory can just replace repos if I decide to use ado.net or go with different database. But, I don t see a good clean way to realize lazy loading, and how to control DbContext/connection life time. Say, I have IRepository interface with CRUD methods, how would I load a List of addresses that belong to a given user ? Making methods like GetAddressListByUserId looks ugly, wrong, and will make me to create a bunch of methods that are just as ugly, and make little sense when using ORM.
I m sure this problem been solved like million times, and hope there s a solution somewhere..
还有一个关于储存模式的问题——你如何处理属于财产的物体? E.g. 用户有一份地址清单,你如何检索该清单? 建立地址存放处? 在投管处,地址标的不一定要提到用户,也不必提及有背书的Id领域,而是必须提到所有。 更多的代码、更多的暴露特性。