我曾经实现过我的存储库类,如下所示
public Class MyRepository
{
private MyDbContext _context;
public MyRepository(MyDbContext context)
{
_context = context;
}
public Entity GetEntity(Guid id)
{
return _context.Entities.Find(id);
}
}
Run Code Online (Sandbox Code Playgroud)
However I recently read this article which says that's a bad practice to have data context as a private member in your repository: http://devproconnections.com/development/solving-net-scalability-problem
Now, theoretically the article is right: since DbContext implements IDisposable the most correct implementation would be the following.
public Class MyRepository
{
public Entity GetEntity(Guid id)
{
using (MyDbContext context = …Run Code Online (Sandbox Code Playgroud) 在我的应用程序中,绝不能删除数据库中的数据.
实体有一个属性Deleted,可以设置为true或false.
虚拟删除的实体不能从数据库中出去,从应用程序的角度看它们不能存在.
我通过在我的数据访问层中创建GetAll-方法(例如GetAllUsers)来管理它.这些方法只返回flaged为NOT删除的实体(!Deleted),所有其他方法(例如GetUserById)都使用这些方法检索数据.
见下面的例子......
public IEnumerable<User> GetAllUsers()
{
return _dataContext.Users.Where(element => !element.Deleted);
}
public User GetUserById(string userName)
{
return GetAllUsers().FirstOrDefault(elt => elt.UserName.Equals(userName));
}
Run Code Online (Sandbox Code Playgroud)
从可靠性的角度来看,这种架构非常好,因为我确信我总是提取未删除的实体,但我担心这样做效率不高.
我的问题非常简单:我的应用程序是select * from User每次请求特定用户时从User表()中提取所有数据,还是实体框架足够智能以理解我想要的内容并转换为类似以下内容的SQL查询:select * from User where userName = @userName?
如果我每次需要单个用户时从数据库中提取所有数据,那么如何更改我的代码以便创建正确的查询?我想保留集中化,这样我就不必指定了!在每个LINQ查询中都删除了.
我正在创建一个多层应用程序,将asp.net mvc应用程序作为最高层.
该体系结构如下(--->表示引用):
表示层--->服务层--->业务层---->数据访问层---->数据库
此外,还有一个名为"Infrastracture"的层,它被所有层引用.
每一层都有自己的实体.例如:在表示层中,我们可能在服务层UserDTO中具有UserViewModel,在业务层UserBDO中,最后在数据访问层中具有User.
automapper用于自动化不同类型之间的转换.
我读到一些开发人员建议将映射创建放在Global.asax中,但很明显,如果你有一个多层应用程序,你就无法在那里创建所有映射.您无法在表示层中将User与UserBDO映射.
所以,我要求用最干净的方法来管理多层应用程序中的映射集中化.您甚至可以建议更改体系结构.