【问题标题】:Can't access repository to get object in visual studio MVC无法访问存储库以在 Visual Studio MVC 中获取对象
【发布时间】:2015-03-06 11:45:10
【问题描述】:

在控制器中,我试图获得“等级”,使用:

 Grade g = gradeRepository.FindById(1);

findById 在 GradeRepository 中声明:

public class GradeRepository : IGradeRepository
{
private ProjectContext context;
private DbSet<Grade> grades;

public GradeRepository(ProjectContext context)
{
    this.context = context;
    grades = context.Grades;
}

public IQueryable<Grade> FindAll()
{
    return grades.OrderBy(g => g.name);
}

public Grade FindById(int gradeId)
{
    return grades.Include(l => l.DeterminateTableProp).FirstOrDefault(g => g.GradeInt == gradeId);
}

public void Remove(Grade grade)
{
    grades.Remove(grade);
}

public void SaveChanges()
{
    context.SaveChanges();
}


}

服务在 nijectwebcommon 文件中正确注册:

private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IContinentRepository>().To<ContinentRepository>().InRequestScope();
            kernel.Bind<IGradeRepository>().To<GradeRepository>().InRequestScope();
            kernel.Bind<ProjectContext>().ToSelf().InSingletonScope();
        }

这可能是什么问题? 我所做的与我正在使用的另一个存储库完全相同。

【问题讨论】:

  • 在代码中运行 Grade g = gradeRepository.FindById(1); 会发生什么?
  • 它抛出一个异常(被捕获并重定向到另一个页面)。
  • 异常类型是什么?留言?
  • SqlException。 EntityFramework.SqlServer.dll 中发生“System.Reflection.TargetInvocationException”类型的异常,但未在用户代码中处理附加信息:调用的目标已导致异常。

标签: c# visual-studio


【解决方案1】:

回答

检查InnerException property of the TargetInvocationException 以找出问题所在。

InnerException 的重要性

这就是您需要查看InnerException 的原因。通过reflection 调用了一些方法,可能是工厂方法。该方法引发了异常,并且该异常隐藏在TargetInvocationExceptionInnerException 属性中,因为这就是反射调用方法异常所发生的情况。他们被隐藏起来。因此,您需要检查InnerException 以找出真正出了什么问题。

TargetInvocationException 中的The intro and remarks on MSDN tell the story 相当不错。

这可能是什么问题?

通过查看您的代码,可能是称为 GetConstructorForType 工厂方法的反射,如果 Grade 缺少默认构造函数,它将引发异常。

internal static ConstructorInfo GetConstructorForType(Type type)
{
    System.Diagnostics.Debug.Assert(type != null);
    ConstructorInfo ci = type.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null, System.Type.EmptyTypes, null);
        if (null == ci)
        {
            ThrowConstructorNoParameterless(type);
        }
    return ci;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多