[英]DbContext and Interface in HTTPPost action
I am using StructureMap for my dependency resolving. 我正在使用StructureMap进行依赖关系解析。 I am faced with an issue I don't know how to solve as the only way to make a form posting I understand will end up being without dependency injection which negate the whole essence of having StructureMap in my project.
我面临着一个我不知道该如何解决的问题,因为我理解进行表单发布的唯一方法最终将是没有依赖项注入,这会否定在我的项目中拥有StructureMap的全部实质。 The error is that I don't have
Add
method in my IdbContext Model. 错误是我的IdbContext模型中没有
Add
方法。 Below is my approach. 下面是我的方法。
I have a Model named Module defined as below 我有一个名为Module的模型,定义如下
public class Module
{
public virtual int ID { get; set; }
public virtual string Name { get; set; }
public virtual DateTime? DateCreated { get; set; }
public virtual string ModuleDescription { get; set; }
}
and an interface defined as below. 以及如下定义的接口。
public interface ISolnetDataSource
{
IQueryable<Module> Modules { get; }
void Save();
}
A DbContext like below 如下所示的DbContext
public class CMSDB : DbContext, ISolnetDataSource
{
public CMSDB() : base("DefaultConnection")
{
}
public DbSet<Module> Modules { get; set; }
void ISolnetDataSource.Save()
{
SaveChanges();
}
IQueryable<Module> ISolnetDataSource.Modules
{
get { return Modules; }
}
}
and my controller defined as 而我的控制器定义为
[HttpPost]
public ActionResult Index(CreateModulesViewModels module)
{
ViewBag.ListModule = _db.Modules.ToList();
if (ModelState.IsValid)
{
var model = new CreateModulesViewModels();
var CreateModule = new Module();
CreateModule.Name = module.Name;
CreateModule.ModuleDescription = module.ModuleDescription;
CreateModule.DateCreated = DateTime.Now;
//_db.modules.Add(CreateModule);
_db.Save();
return View(model);
}
return View(module);
}
The challenge I have with this is that I could'nt do _db.modules.Add(CreateModule)
(the commented line in the controller) so as to add a new record. 我面临的挑战是我无法执行
_db.modules.Add(CreateModule)
(控制器中的注释行)以添加新记录。 What I'm doing wrong. 我做错了。 I want to do this using the best approach applicable.
我想使用适用的最佳方法来做到这一点。
关于什么:
_db.modules.Entry(CreateModule).State = System.Data.EntityState.Added;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.