Ter*_*rry 4 c# ef-code-first dbcontext
我前面问了一个问题,为什么当我联合两个实体集合时,默认的相等比较器似乎不起作用.
EF Code First - Linq to Entities Union EqualityComparer
答案是由于我使用了DbContext的两个差异实例,因此引用了不同的内容.
所以现在我想在整个请求中分享我的DbContent.我看到一些"复杂"的例子,但我想我会尝试一个更简单的解决方案.
所以我创建了一个IDbContext接口,它简单地概述了我的实体
public interface IDbContext {
int SaveChanges();
DbSet<News> News { get; set; }
DbSet<Category> Categories { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的DbContext然后实现如下:
public class SiteContext : DbContext, IDbContext {
public DbSet<News> News { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的两个存储库(NewsRepository和CategoryRespository)中,我将IDbContext作为构造函数参数
IDbContext _db;
public NewsRepository(IDbContext db) {
_db = db;
}
Run Code Online (Sandbox Code Playgroud)
所以现在我假设如果我将IDbContext绑定到请求范围中的SiteContext,我的存储库将共享相同的上下文?
kernel.Bind<IDbContext>().To<SiteContext>().InRequestScope();
Run Code Online (Sandbox Code Playgroud)
但是,当我从上一个问题再次尝试我的工会时,我仍然收到重复的实体!我做错了什么?如何在一个请求中确实使用相同的上下文?
因为构建每个存储库时,Ninject将为每个存储库提供一个新的SiteContext实例.这就是为什么它不起作用.使用单元工作实现是一个好主意,这意味着所有存储库都使用相同的上下文.
UnitOfWork将构建一个IDbContext.
像这样的事情会起作用
private IDbContext _context;
public UnitOfWork(IDbContext context)
{
_context = context
}
private _INewsRepository;
public INewsRepoitory
{
get{
if(_INewsRepository == null)
{
_INewsRepository = new NewsREpository(_context);
return _INewsRepository;
}
else
{
return _INewsRepository;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4464 次 |
| 最近记录: |