是否可以将依赖项注入迁移中(使用EF-Core代码优先迁移)? [英] Can I inject dependency into migration (using EF-Core code-first migrations)?

本文介绍了是否可以将依赖项注入迁移中(使用EF-Core代码优先迁移)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将 IConfiguration 注入到迁移中(在构造函数中),但出现异常:未为此对象定义无参数构造函数."

I tried to inject IConfiguration into the migration (in constructor), and got exception: "No parameterless constructor defined for this object."

任何解决方法?

推荐答案

您不能,迁移需要能够在应用程序上下文之外运行.

you cannot, the migrations need to be able to run outside the context of your application.

由于Entity-framework命令行工具分析了您的代码,但未运行startup.cs类.

Since the Entity-framework command-line tool analyzes your code but does not run the startup.cs class.

也不建议这样做.您的迁移应该非常简单,并且不依赖任何内容.如果这样做的话,可能会导致主要的运行时副作用,即缺少配置可能会导致生产中缺少表或列.

Also it is not advisable. your migrations should be plain simple and not depend on anything. if it would, it could lead to major runtime side-effects where missing config could lead to missing tables or columns in production.

如果涉及很多小的/相等/手动更改.最好的方法是生成您的迁移文件.为什么?这样,您的迁移将是确定性的:您知道结果如何.如果您的迁移中的一行失败了,这很简单,也很清楚为什么这样容易修复.

If it involves a lot of small/equal/manual changes. Best way is to generate your migration file. Why? This way your migration will be deterministic: you know what the outcome will be. If a line in your migration fails, it is simple and clear why that is and easily(er) fixable.

这篇关于是否可以将依赖项注入迁移中(使用EF-Core代码优先迁移)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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