嗨,这与我以前的问题有关。
EFCodeFirst : 无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象
根据我上一个问题的答案中给出的参考,我不确定在使用 Ninject 和 MVC 时如何正确实现我的 DbContext 的使用。有没有人推荐如何做到这一点的例子?谢谢。
我确实在这里看到了这个 1 示例:How to handle DBContext when using Ninject 但我不确定这如何适合我项目的当前结构。
这是我的一个存储库和界面的示例,其他存储库几乎相同,目前都创建一个新上下文,我可能会更改它以将上下文注入存储库,但我认为这还不够.
public interface IRepository<T> where T : Entity {
IQueryable<T> All { get; }
T Find(int id);
void InsertOrUpdate(T entity);
void Delete(int id);
void Save();
}
public class RecipeRepository : IRepository<Recipe>
{
private EatRateShareDbContext context = new EatRateShareDbContext();
public IQueryable<Recipe> All
{
get { return context.Recipes; }
}
public Recipe Find(int id)
{
return context.Recipes.Find(id);
}
public void InsertOrUpdate(Recipe recipe)
{
if (recipe.Id == default(int))
{
// New entity
context.Recipes.Add(recipe);
} else
{
// Existing entity
context.Entry(recipe).State = EntityState.Modified;
}
}
public void Delete(int id)
{
var recipe = context.Recipes.Find(id);
context.Recipes.Remove(recipe);
}
public void Save()
{
try
{
context.SaveChanges();
}
catch (DbEntityValidationException databaseException)
{
foreach (var validationErrors in databaseException.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
}
}
}
}
}
这是我的 DbContext
public class ERSDbContext : DbContext
{
public DbSet<Recipe> Recipes { get; set; }
public DbSet<Ingredient> Ingredients { get; set; }
public DbSet<Review> Reviews { get; set; }
public DbSet<Course> Courses { get; set; }
public DbSet<Cuisine> Cuisines { get; set; }
public DbSet<Member> Members { get; set; }
public DbSet<Step> Steps { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// have to specify these mappings using the EF Fluent API otherwise I end up with
// the foreign key fields being placed inside the Recipe and Member tables, which wouldn't
// give a many-to-many relationship
modelBuilder.Entity<Recipe>()
.HasMany(r => r.Members)
.WithMany(m => m.Recipes)
.Map(x => {
x.ToTable("Cookbooks"); // using a mapping table for a many-to-many relationship
x.MapLeftKey("RecipeId");
x.MapRightKey("MemberId");
});
modelBuilder.Entity<Recipe>()
.HasRequired(x => x.Author)
.WithMany()
.WillCascadeOnDelete(false);
}
}
我使用 Ninject 将我的存储库注入到控制器中,如图所示
public class RecipesController : Controller
{
private readonly IRepository<Member> memberRepository;
private readonly IRepository<Course> courseRepository;
private readonly IRepository<Cuisine> cuisineRepository;
private readonly IRepository<Recipe> recipeRepository;
public RecipesController(IRepository<Member> memberRepository, IRepository<Course> courseRepository, IRepository<Cuisine> cuisineRepository, IRepository<Recipe> recipeRepository)
{
this.memberRepository = memberRepository;
this.courseRepository = courseRepository;
this.cuisineRepository = cuisineRepository;
this.recipeRepository = recipeRepository;
}
...
}
对于 Ninject,我使用的是创建 NinjectWebCommon 类的 Nuget 插件,以下是我当前的绑定。
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IRepository<Recipe>>().To<RecipeRepository>();
kernel.Bind<IRepository<Member>>().To<MemberRepository>();
kernel.Bind<IRepository<Cuisine>>().To<CuisineRepository>();
kernel.Bind<IRepository<Course>>().To<CourseRepository>();
kernel.Bind<IRepository<Review>>().To<ReviewRepository>();
}