小编Aid*_*din的帖子

DbSet.Cast <TEntity>()错误:无法从非泛型DbSet为"实体"类型的对象创建DbSet <IEntity>

版本信息:

我正在使用C#4.5,Entity Framework 6.0和MEF.

代码和单元测试

我创建了一个测试项目来解释这个问题:https: //skydrive.live.com/redir?resid = E3C97EC293A34048!2234

请打开UnitTest项目并尝试运行TestIfItWorks()单元测试.

问题

我想将非泛型DbSet转换为其通用版本,但我得到以下异常InvalidCastException: Cannot create a DbSet<IUser> from a non-generic DbSet for objects of type 'User':

var nonGeneric = context.Set(typeof(User));
var generic = nonGeneric.Cast<IUser>(); //Exception in here
Run Code Online (Sandbox Code Playgroud)

User类正在实现IUser,所以你会认为强制转换不应该是一个问题,除非DbSet代码仅限于具体的类(我希望不是我需要创建一个围绕非泛型DbSet的包装器将它转换为泛型DbSet或找到当前DbSet实现的替代方案).

如果您想知道我为什么使用接口,即使它们目前不受Microsoft支持,我会给您一些解释(希望这会过滤掉"不要那样做"而不是提供解决方案的响应):

我正在使用MEF和EntityFramework来创建一个松散耦合的数据层引擎,通过它我可以为每个项目提供实体(及其相应的配置).我一直在广泛使用Interfaces来定义引擎.使用MEF在运行时发现元数据和上下文中实体的具体实现.

摘自代码

[TestMethod]
public void TestIfItWorks()
{
    //TODO: Please open the App.Config and change the PluginsPath to match the Plugins folder in your machine.

    using (var dbContext = new MyContext()) //Please ignore this line for now. This was …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework casting mef dbset

6
推荐指数
1
解决办法
7159
查看次数

手动将DbContext提供给DbMigrator

Platform .NET 4.5和Entity Framework 6.

问题 我有以下代码来执行迁移:

//The following function just returns an object of the Configuration() class 
//generated by code migrations
var migratorConfig = currentMigrationProvider.CreateDbMigrationConfiguration(); 
var dbMigrator = new System.Data.Entity.Migrations.DbMigrator(migratorConfig);
dbMigrator.Update();
Run Code Online (Sandbox Code Playgroud)

问题是Update()函数尝试创建我的DbContext类的实例,出于一些好的原因,我需要手动创建上下文并将其提供给dbMigrator.那可能吗?怎么样?

c# entity-framework dbcontext ef-migrations dbmigrator

5
推荐指数
1
解决办法
2508
查看次数

使用Webpack 2和awesome-typescript-loader解决baseUrl和路径问题

我想设置我的项目,所以我在哪里使用下面的行:

import { BlahBlahService } from '@blahblah/core/BlahBlahService';
Run Code Online (Sandbox Code Playgroud)

它解决了:

./dist/blahblah/core/BlahBlahService

我已经阅读了在线资源并应用了指示的设置(我也在下面包含).这适用于Visual Studio Code; 即它没有向我显示错误因此它能够在tsconfig上正确读取我的设置并理解它.我想让同样的事情发生在Webpack上.

但是我收到以下错误:

./xxxxxxxxxxx.ts中的错误找不到模块:错误:无法解析'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'中的'@ blahblah/core/BlahBlahService'

我的Web应用程序中有以下设置:

  • Angular 2版本2.2.0
  • 打字稿版本2.0.8
  • Webpack版本2.1.0-beta.26
  • awesome-typescript-loader版本2.2.4

我的tsconfig中也有以下内容:

"compilerOptions": {

    ...

    "baseUrl": ".",
    "paths": {
       "@blahblah/core": ["./dist/blahblah/core"],
       "@blahblah/core/*": ["./dist/blahblah/core/*"],
    }

    ...

 }
Run Code Online (Sandbox Code Playgroud)

我在webpack.js文件中有以下设置:

plugins: [

    ...

    new TsConfigPathsPlugin(),

    ...
],
Run Code Online (Sandbox Code Playgroud)

typescript tsconfig webpack webpack-2

5
推荐指数
1
解决办法
3254
查看次数