首页 > 解决方案 > 从 DbContext 继承类时 MS Office 加载项错误

问题描述

我正在尝试在 Visual Studio 16.6.1 目标中创建一个 Word VSTO 加载项.NET Framework 4.8项目。我想使用Microsoft.EntityFrameworkCore.Sqlite来访问数据库中的信息。但是,一旦我添加了一个继承自 的类DbContext,我就无法再构建该项目。我收到错误报告:

The "FindRibbons" task failed unexpectedly. 
System.IO.FileNotFoundException: Could not load file or assembly 'WordAddInTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

WordAddinTest 是我的项目的名称。

我可以使用这些最少的步骤来重现它:

  1. 创建 Word VSTO 加载项类型的新 Visual Basic 项目。
  2. 将名称设置为 WordAddinTest,并将框架设置为 Framework .NET Framework 4.8。
  3. 使用 Nuget 包管理器,安装Microsoft.EntityFrameworkCore.Sqlite.
  4. 将 ThisAddIn.vb 中的默认代码替换为以下内容:

代码:

Imports Microsoft.EntityFrameworkCore

Public Class ThisAddIn
    Private Sub ThisAddIn_Startup() Handles Me.Startup
    End Sub

    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown
    End Sub
End Class

Public Class TestClass
    Public Property Id As Integer
    Public Property Title As String
End Class

Public Class TestContext
    'Inherits DbContext
    'NOTE: If the line above is excluded, it will compile (but obviously without EntityFramework support)

    Public Property TestProperty As DbSet(Of TestClass)
End Class

这将毫无问题地编译、运行和调试。

但是,取消注释指示 TestContext 继承自 DbContext 的行,它不再编译,并且错误列表显示以下错误:

The "FindRibbons" task failed unexpectedly.
System.IO.FileNotFoundException: Could not load file or assembly 'WordAddInTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
File name: 'WordAddInTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'

Server stack trace: 
   at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection)
   at System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection)
   at System.Reflection.Assembly.Load(String assemblyString)
   at System.UnitySerializationHolder.GetRealObject(StreamingContext context)
   at System.Runtime.Serialization.ObjectManager.ResolveObjectReference(ObjectHolder holder)
   at System.Runtime.Serialization.ObjectManager.DoFixups()
   at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
   at System.Runtime.Remoting.Channels.CrossAppDomainSerializer.DeserializeObject(MemoryStream stm)
   at System.Runtime.Remoting.Messaging.SmuggledMethodReturnMessage.FixupForNewAppDomain()
   at System.Runtime.Remoting.Channels.CrossAppDomainSink.SyncProcessMessage(IMessage reqMsg)

Exception rethrown at [0]: 
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at Microsoft.Build.Framework.ITask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()

WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog]. WordAddInTest

注意最后关于 Fusion Logging 的建议,如果我设置该注册表值,它会添加以下信息:

=== Pre-bind state information ===
LOG: DisplayName = WordAddInTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
 (Fully-specified)
LOG: Appbase = file:///C:/applications/programming/Visual Studio 2019 Community/MSBuild/Current/Bin/
LOG: Initial PrivatePath = NULL
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\applications\programming\Visual Studio 2019 Community\MSBuild\Current\Bin\MSBuild.exe.Config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/applications/programming/Visual Studio 2019 Community/MSBuild/Current/Bin/WordAddInTest.DLL.
LOG: Attempting download of new URL file:///C:/applications/programming/Visual Studio 2019 Community/MSBuild/Current/Bin/WordAddInTest/WordAddInTest.DLL.
LOG: Attempting download of new URL file:///C:/applications/programming/Visual Studio 2019 Community/MSBuild/Current/Bin/WordAddInTest.EXE.
LOG: Attempting download of new URL file:///C:/applications/programming/Visual Studio 2019 Community/MSBuild/Current/Bin/WordAddInTest/WordAddInTest.EXE.   WordAddInTest

Visual Studio 正在 MSBuild 目录中查找我的加载项 DLL。

只是不能在 VSTO 插件项目中使用实体框架吗?为什么它无法编译还有另一种合乎逻辑的解释吗?我还没有找到任何其他关于相同问题的报告,我无法想象我是第一个尝试它的人。

我意识到实际使用 EntityFramework 来访问数据库需要更多,但这是一个编译错误,所以它甚至没有那么远。

感谢您提供的任何帮助。

更新

以下是.vbproj(等效于 .csproj)文件,以防它有助于识别/解决问题:

<Project ToolsVersion="16.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <!--
    This section defines project-level properties.

    AssemblyName
      Name of the output assembly.
    Configuration
      Specifies a default value for debug.
    OutputType
      Must be "Library" for VSTO.
    Platform
      Specifies what CPU the output of this project can run on.
    NoStandardLibraries
      Set to "false" for VSTO.
    RootNamespace
      In C#, this specifies the namespace given to new files. In VB, all objects are
      wrapped in this namespace at runtime.
  -->
  <PropertyGroup>
    <ProjectTypeGuids>{BAA0C2D2-18E2-41B9-852F-F413020CAA33};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{A4902970-1F65-45A0-AED0-5B3398DFE0CD}</ProjectGuid>
    <OutputType>Library</OutputType>
    <NoStandardLibraries>false</NoStandardLibraries>
    <RootNamespace>WordAddinTest</RootNamespace>
    <AssemblyName>WordAddinTest</AssemblyName>
    <LoadBehavior>3</LoadBehavior>
    <TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
    <DefineConstants>VSTO40</DefineConstants>
    <BootstrapperEnabled>true</BootstrapperEnabled>
    <BootstrapperComponentsLocation>HomeSite</BootstrapperComponentsLocation>
  </PropertyGroup>
  <ItemGroup>
    <BootstrapperPackage Include="Microsoft.VSTORuntime.4.0">
      <Visible>False</Visible>
      <ProductName>Microsoft Visual Studio 2010 Tools for Office Runtime %28x86 and x64%29</ProductName>
      <Install>true</Install>
    </BootstrapperPackage>
  </ItemGroup>
  <PropertyGroup>
    <!--
      OfficeApplication
        Add-in host application
    -->
    <OfficeApplication>Word</OfficeApplication>
  </PropertyGroup>
  <!--
    This section defines properties that are set when the "Debug" configuration is selected.

    DebugSymbols
      If "true", create symbols (.pdb). If "false", do not create symbols.
    DefineConstants
      Constants defined for the preprocessor.
    EnableUnmanagedDebugging
      If "true", starting the debugger will attach both managed and unmanaged debuggers.
    Optimize
      If "true", optimize the build output. If "false", do not optimize.
    OutputPath
      Output path of project relative to the project file.
    WarningLevel
      Warning level for the compiler.
  -->
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
    <DebugSymbols>true</DebugSymbols>
    <DebugType>full</DebugType>
    <Optimize>false</Optimize>
    <OutputPath>bin\Debug\</OutputPath>
    <EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
    <DefineConstants>$(DefineConstants);DEBUG;TRACE</DefineConstants>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <!--
    This section defines properties that are set when the "Release" configuration is selected.

    DebugSymbols
      If "true", create symbols (.pdb). If "false", do not create symbols.
    DefineConstants
      Constants defined for the preprocessor.
    EnableUnmanagedDebugging
      If "true", starting the debugger will attach both managed and unmanaged debuggers.
    Optimize
      If "true", optimize the build output. If "false", do not optimize.
    OutputPath
      Output path of project relative to the project file.
    WarningLevel
      Warning level for the compiler.
  -->
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
    <DebugType>pdbonly</DebugType>
    <Optimize>true</Optimize>
    <OutputPath>bin\Release\</OutputPath>
    <EnableUnmanagedDebugging>false</EnableUnmanagedDebugging>
    <DefineConstants>$(DefineConstants);TRACE</DefineConstants>
    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <!--
    This section specifies references for the project.
  -->
  <ItemGroup>
    <Reference Include="Accessibility" />
    <Reference Include="System" />
    <Reference Include="System.Data" />
    <Reference Include="System.Drawing" />
    <Reference Include="System.Windows.Forms" />
    <Reference Include="System.Xml" />
    <Reference Include="System.Core" />
    <Reference Include="System.Xml.Linq" />
    <Reference Include="System.Data.DataSetExtensions" />
    <Reference Include="Microsoft.CSharp" />
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Microsoft.Office.Tools.v4.0.Framework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.VisualStudio.Tools.Applications.Runtime, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Office.Tools, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Office.Tools.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <Private>False</Private>
    </Reference>
    <Reference Include="Microsoft.Office.Tools.Word, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <Private>False</Private>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Microsoft.Office.Tools.Common.v4.0.Utilities, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
      <Private>True</Private>
    </Reference>
  </ItemGroup>
  <ItemGroup>
    <Reference Include="Office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">
      <Private>False</Private>
      <EmbedInteropTypes>true</EmbedInteropTypes>
    </Reference>
    <Reference Include="Microsoft.Office.Interop.Word, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c">
      <Private>False</Private>
      <EmbedInteropTypes>true</EmbedInteropTypes>
    </Reference>
    <Reference Include="stdole, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
      <Private>False</Private>
    </Reference>
  </ItemGroup>
  <!--
    This section defines the user source files that are part of the project.

    A "Compile" element specifies a source file to compile.
    An "EmbeddedResource" element specifies an .resx file for embedded resources.
    A "None" element specifies a file that is not to be passed to the compiler (for instance, 
    a text file or XML file).
    The "AppDesigner" element specifies the directory where the application properties files
    can be found.
  -->
  <ItemGroup>
    <Compile Include="Model.cs" />
    <Compile Include="Properties\AssemblyInfo.cs">
      <SubType>Code</SubType>
    </Compile>
    <EmbeddedResource Include="Properties\Resources.resx">
      <Generator>ResXFileCodeGenerator</Generator>
      <LastGenOutput>Resources.Designer.cs</LastGenOutput>
      <SubType>Designer</SubType>
    </EmbeddedResource>
    <Compile Include="Properties\Resources.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Resources.resx</DependentUpon>
    </Compile>
    <None Include="WordAddinTest_TemporaryKey.pfx" />
    <None Include="Properties\Settings.settings">
      <Generator>SettingsSingleFileGenerator</Generator>
      <LastGenOutput>Settings.Designer.cs</LastGenOutput>
    </None>
    <Compile Include="Properties\Settings.Designer.cs">
      <AutoGen>True</AutoGen>
      <DependentUpon>Settings.settings</DependentUpon>
    </Compile>
    <Compile Include="Ribbon1.cs" />
    <Compile Include="ThisAddIn.cs">
      <SubType>Code</SubType>
    </Compile>
    <None Include="ThisAddIn.Designer.xml">
      <DependentUpon>ThisAddIn.cs</DependentUpon>
    </None>
    <Compile Include="ThisAddIn.Designer.cs">
      <DependentUpon>ThisAddIn.Designer.xml</DependentUpon>
    </Compile>
    <AppDesigner Include="Properties\" />
  </ItemGroup>
  <ItemGroup>
    <EmbeddedResource Include="Ribbon1.xml" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite">
      <Version>3.1.4</Version>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools">
      <Version>3.1.4</Version>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
  </ItemGroup>
  <PropertyGroup>
    <VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
    <VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
  </PropertyGroup>
  <PropertyGroup>
    <SignManifests>true</SignManifests>
  </PropertyGroup>
  <PropertyGroup>
    <ManifestKeyFile>WordAddinTest_TemporaryKey.pfx</ManifestKeyFile>
  </PropertyGroup>
  <PropertyGroup>
    <ManifestCertificateThumbprint>002EE54C6C297029AF8A7691A5DAC8F51DACA96A</ManifestCertificateThumbprint>
  </PropertyGroup>
  <!-- Include the build rules for a C# project. -->
  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
  <!-- Include additional build rules for an Office application add-in. -->
  <Import Project="$(VSToolsPath)\OfficeTools\Microsoft.VisualStudio.Tools.Office.targets" Condition="'$(VSToolsPath)' != ''" />
  <!-- This section defines VSTO properties that describe the host-changeable project properties. -->
  <ProjectExtensions>
    <VisualStudio>
      <FlavorProperties GUID="{BAA0C2D2-18E2-41B9-852F-F413020CAA33}">
        <ProjectProperties HostName="Word" HostPackage="{29A7B9D7-A7F1-4328-8EF0-6B2D1A56B2C1}" OfficeVersion="15.0" VstxVersion="4.0" ApplicationType="Word" Language="cs" TemplatesPath="" DebugInfoExeName="#Software\Microsoft\Office\16.0\Word\InstallRoot\Path#WINWORD.EXE" DebugInfoCommandLine="/x" AddItemTemplatesGuid="{51063C3A-E220-4D12-8922-BDA915ACD783}" />
        <Host Name="Word" GeneratedCodeNamespace="WordAddinTest" IconIndex="0">
          <HostItem Name="ThisAddIn" Code="ThisAddIn.cs" CanonicalName="AddIn" CanActivate="false" IconIndex="1" Blueprint="ThisAddIn.Designer.xml" GeneratedCode="ThisAddIn.Designer.cs" />
        </Host>
      </FlavorProperties>
    </VisualStudio>
  </ProjectExtensions>
</Project>

标签: c#vb.netentity-framework-coreoffice365vsto

解决方案


推荐阅读