.Net Core2.2升級到3.1小記

.NET Core 3.1 做爲LTS長期支持版本,會提供3年的支持(明年就出.net5),值得升級(嗎)。web

目前主流的第三方包大多都已經提供了支持,2.x => 3.1仍是變化不是特別多,EF Core坑就大咯,謹慎。app

 

ASP.NET Core 3.1 的新增功能框架

https://docs.microsoft.com/zh-cn/aspnet/core/release-notes/aspnetcore-3.1?view=aspnetcore-3.1ide

EF Core 3.0重大改變ui

https://docs.microsoft.com/zh-cn/ef/core/what-is-new/ef-core-3.0/breaking-changesspa

 

1,將VS2019更新到16.4.x,會自動安裝3.1的SDK。.net

 

2,將項目目標框架升級到3.1,右鍵項目 - 屬性 - 目標框架,或者修改csproj文件。code

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

 

3,WEB項目中Program.cs文件,WebHost 改成 Hostblog

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

 

4,WEB項目中Startup.csget

ConfigureServices 方法中 services.AddMvc() 改成 services.AddControllersWithViews()

//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddControllersWithViews();

Configure 方法中 app.UseMvc() 改成 app.UseRouting() 與 app.UseEndpoints()

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();
    app.UseAuthorization();

    app.UseRouting(); app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}"); });
}

 

5,更新全部(相關)nuget包到最新

 

6,從新生成解決方案,報錯 The project .... must provide a value for Configuration.

從 Web 項目中移除 Microsoft.AspNetCore... 的 PackageReference,由於已經包含在3.1的目標框架內了。

<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />

 

大功告成,至少編譯經過了,運行中目前只碰到一個坑。

A tracking query projects owned entity without corresponding owner in result.Owned entities cannot be tracked without their owner. Either include the owner entity in the result or make query non-tracking using AsNoTracking().

AutoMapper的ProjectTo<>致使,暫時加了個AsNoTracking()解決問題,根據報錯信息來看還有另外一種解決方案。

public IEnumerable<UserDto> GetAll()
{
    return _userRepository.GetAll(tracking: false)
        .OrderByDescending(s => s.Id)
        .ProjectTo<UserDto>(_mapper.ConfigurationProvider)
        .AsEnumerable();
}
相關文章
相關標籤/搜索