使用Unity时出现实体框架错误 [英] Entity Framework Error when using Unity

查看:79
本文介绍了使用Unity时出现实体框架错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试解析我的服务类时,出现一个错误,提示无法构建 DbContext ,因为它是一个抽象类.错误消息在这里:

On trying to resolve my service class, I'm getting an error that DbContext cannot be constructed because it's an abstract class. The error message is here:

Unity.Exceptions.ResolutionFailedException: 'Resolution of the dependency failed, type = 'MyService.MyClass', name = '(none)'.
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, System.Data.Common.DbConnection, is an abstract class and cannot be constructed. Are you missing a type mapping?
-----------------------------------------------
At the time of the exception, the container was: 
  Resolving ...
      ...
          Resolving MyApp.MyRepository,(none)
          Resolving parameter 'myDbContext' of constructor MyApp.MRepository(MyApp.IMyDbContext myDbContext)
          ...
              Resolving parameter 'existingConnection' of constructor MyApp.MyDbContext(System.Data.Common.DbConnection existingConnection, System.Data.Entity.Infrastructure.DbCompiledModel model, System.Boolean contextOwnsConnection)
                Resolving System.Data.Common.DbConnection,(none)
'

DBContext看起来像这样:

The DBContext looks like this:

public class MyDbContext : System.Data.Entity.DbContext, IMyDbContext
{
    public MyDbContext()
        : base("MainConnectionString")
    {
    }

我的猜测是EF在配置文件中寻找连接字符串;但是定义了连接字符串:

My guess is that EF looks for a connection string in the config file; but the connection string is defined:

<connectionStrings>
    <add name="MainConnectionString" connectionString="Server=.\SQLEXPRESS;Database=MyDB;User Id= . . ." providerName="System.Data.SqlClient" />
</connectionStrings>

统一注册:

因此,我的问题是EF如何计算出该类的构造方式,很明显我在配置中丢失了一些东西.

My question, therefore, is how does EF work out how to construct this class, as clearly I'm missing something in the configuration.

UnityContainer container = new UnityContainer();
container.RegisterType<IMyDbContext, MyDbContext>();
container.RegisterType<IMyRepository, MyRepository>();
container.RegisterInstance<IUnityContainer>(container);

推荐答案

我设法通过更改注册以显式传递连接字符串名称来使其正常工作:

I managed to get this working, by changing the registration to explicitly pass the connection string name:

UnityContainer container = new UnityContainer();
container.RegisterType<IMyDbContext, MyDbContext>(new InjectionConstructor("MainConnectionString"));
. . .
container.RegisterInstance<IUnityContainer>(container);

这篇关于使用Unity时出现实体框架错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆