您好,我正在使用实体框架核心来开发Web api(.net核心)。我创建了如下的上下文类。
public class TimeSheetContext : DbContext
{
public TimeSheetContext(DbContextOptions<TimeSheetContext> options)
: base(options)
{
}
public DbSet<Project> Projects { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<TimeSheetData> timeSheets { get; set; }
public DbSet<Week> weeks { get; set; }
}
然后我使用下面的代码添加时间表数据。
public void SaveTimeSheet(TimeSheetData timeSheet)
{
using (var context = new TimeSheetContext())
{
var std = context.timeSheets.Add(timeSheet);
context.SaveChanges();
}
}
[using (var context = new TimeSheetContext())
在这里,我遇到了以下错误。
没有参数对应于所需的形式参数的选项timesheetcontext.timesheetcontext(dbcontextoptions)
我在启动时添加了以下代码。
services.AddDbContext<TimeSheetContext>(opt =>
opt.UseSqlServer(Configuration.GetConnectionString("TimeSheet")));
然后我像下面那样使用。
public class TimeSheet : ITimesheet
{
private readonly TimeSheetContext _context;
public TimeSheet(TimeSheetContext context)
{
_context = context;
}
public TimeSheet GetTimeSheet(string userid, string weekid)
{
throw new NotImplementedException();
}
public void SaveTimeSheet(TimeSheetData timeSheet)
{
var std = _context.timeSheets.Add(timeSheet);
_context.SaveChanges();
}
}
然后我尝试如下在启动时注册TimeSheet服务。
services.AddTransient<ITimesheet, TimeSheet>();
现在我开始在时间表附近出现错误,
时间表是一个命名空间,但像类型一样使用
有人可以帮助我找到此错误。任何帮助将不胜感激。谢谢
所以,我相信您有两个错误。
1。时间表是一个命名空间,但像类型一样使用
我相信TimeSheet类存在于以相同文本TimeSheet
结尾的名称空间中。
在DI中指定班级时,您可以使用完全合格的班级<namespace-name>.TimeSheet
以避免此错误。
2。没有参数对应于timesheetcontext.timesheetcontext(dbcontextoptions)
所需的形式参数选项之所以这样,是因为您没有使用DI来使用DbContext对象。
理想情况下,您应按以下方式使用DbContext:
namespace ContosoUniversity.Controllers
{
public class TimeSheetController : Controller
{
private readonly TimeSheetContext _context;
public TimeSheetController(TimeSheetContext context)
{
_context = context;
}
}
}
我希望这可以帮助您解决问题。