我使用 .net 6,当我使用添加带有视图的 ASP.NET Core MVC 控制器时,使用 Entity Framework Core(我在区域中执行此操作)。我收到错误。
我找了很多,但没有找到
错误:
数据库上下文:
namespace PotLearn.DataLayer.Context
{
public class PotLearnContext:DbContext
{
public PotLearnContext(DbContextOptions<PotLearnContext> options)
: base(options)
{
}
#region User
public DbSet<User> Users { get; set; }
#endregion
}
}
程序.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
#region DataBase Context
var connectionString = builder.Configuration.GetConnectionString("PotLearnConnection");
builder.Services.AddDbContext<PotLearnContext>(options => options.UseSqlServer(connectionString));
#endregion
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
app.Run();
如何修复此错误?
谢谢你。
这个问题似乎是版本问题。您的 .NET 6.0 与 Web.CodeGeneration 的版本不匹配。
解决方案 - 1: 转到 NuGet 包管理器(工具 > NuGet 包管理器 > 管理解决方案的 NuGet 包)。然后转到更新并更新其中显示的软件包。
解决方案 - 2: 清理并重建整个解决方案,而不仅仅是项目。
解决方案 - 3:- 如果 解决方案 - 1 不起作用,请转到“浏览”选项卡,然后搜索 Microsoft.VisualStudio.Web.CodeGeneration,并根据您的 .NET 项目,通过选择版本号来安装版本。
希望这有帮助。
在.Net 6中尝试修复此问题很长时间后,当我尝试安装“Microsoft.CodeAnalysis.CSharp.Workspaces”时,碰巧在控制台中读取:
NU1107:检测到 Microsoft.CodeAnalysis.Common 版本冲突。 项目project.xxx来解决这个问题。
项目.xxx -> Microsoft.CodeAnalysis.CSharp.Workspaces 4.2.0 -> Microsoft.CodeAnalysis.Common (= 4.2.0) Microsoft.VisualStudio.Web.CodeGeneration.Utils 6.0.7 -> Microsoft.DotNet.Scaffolding.Shared 6.0.7
更换后我的问题解决了 Microsoft.VisualStudio.Web.CodeGeneration.Utils 与 Microsoft.CodeAnalysis.Common
还有 Microsoft.CodeAnalysis.CSharp.Workspaces 与 Microsoft.DotNet.Scaffolding.Shared
在处理已启动代码生成的项目外部定义的上下文类时,代码生成器似乎失败。 经过彻底调查后,我发现该问题与任何版本的代码生成器或任何相关的软件包无关。问题源于将 Context 类定义在与用于生成代码的程序集(假设是您的 DataLayer 项目)不同的程序集中(假设是 Web 应用程序项目)。我尝试让 Visual Studio 为我创建一个上下文(用于我的目标数据模型)(它这样做了并将其保存在 Web 应用程序项目的 Data 文件夹中),并且代码生成使用该上下文进行工作。我检查了生成的上下文类,并与我的比较,当然除了命名空间之外,没有显着差异。所以我删除了生成的上下文文件。我将类似的文件从 DataLayer 项目复制到 Web 应用程序项目;我编辑了命名空间并解析了引用。我使用 DataLayer 项目中编辑过的类重复该过程,它运行完成时没有错误并生成代码,但如果该类是在外部程序集(或项目)中定义的,它会再次失败。我尝试将文件移出数据文件夹以查看代码生成器是否与其绑定,我发现它不依赖于数据文件夹。 所以我得出的结论是,只有当上下文类与启动代码生成的程序集定义在同一程序集中时,生成才有效。