【问题标题】:Namespace not found error when compiling assembly from files从文件编译程序集时找不到命名空间错误
【发布时间】:2016-04-22 13:59:48
【问题描述】:

我想要实现的是从我生成的 c# 类动态生成一个项目。 该类的内容类似于实体框架代码优先代码生成的内容。内容如下:

namespace ElasticTables
{
    using System;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.ComponentModel.DataAnnotations.KeyAttribute;

    [Table("address")]
    public partial class address
    {

        [Key]
        public decimal id { get; set; }

        public string name { get; set; }
    }
}

我从数据库中的表生成这些文件,然后尝试以编程方式编译它,以便我可以在另一个使用 API 的项目中引用生成的项目。

编译时的主要错误是:

命名空间“System.ComponentModel.DataAnnotations”中不存在类型或命名空间名称“KeyAttribute”(您是否缺少程序集引用?)

找不到类型或命名空间“键”

找不到类型或命名空间“表”。

我正在使用“CSharpCodeProvider”

    var provider = new CSharpCodeProvider();
    var options  = new CompilerParameters
    {
        OutputAssembly  = "ElasticTables.dll",
        CompilerOptions = "/optimize"
    };

我有以下引用的程序集

options.ReferencedAssemblies.Add(Directory.GetCurrentDirectory() + "\\EntityFramework.dll");
options.ReferencedAssemblies.Add(Directory.GetCurrentDirectory() + "\\EntityFramework.SqlServer.dll");

我有一个包含文件路径的字符串数组,称为源,我尝试使用以下行进行编译

CompilerResults results = provider.CompileAssemblyFromFile(options, sources);

非常感谢您的帮助。

【问题讨论】:

  • 顺便说一句,程序集是在哪个目录中创建的?我是否在“OutputAssembly”参数中指定它?谢谢。

标签: c# entity-framework namespaces data-annotations csharpcodeprovider


【解决方案1】:

您需要引用所有需要的程序集(如错误所示),因此您至少需要添加:

options.ReferencedAssemblies.Add("System.dll");
options.ReferencedAssemblies.Add("System.ComponentModel.DataAnnotations.dll");

其他可能需要

关于您问题中的评论,是的,您应该指定options.OutputAssembly

另外,在您生成的代码中:

using System.ComponentModel.DataAnnotations.KeyAttribute;

KeyAttribute 不是命名空间,所以编译时可能会报错。

我也会在命名空间之前使用usings before。这不是严格需要的,也不是错误,但这是常见的做法(这样你就可以确定引用的程序集来自 global 命名空间,而不是你的类所在命名空间的子类[以防万一有名字冲突])

【讨论】:

  • 您的回答有效;我不知道这个程序集在哪里(它的目录),它可能位于 .net 框架文件夹中吗?
  • 除非您指定完整路径,否则将在 GAC (Global Assembly Cache) 中查找引用的程序集,通常为 %windir%\Microsoft.NET\assembly\GAC_[32|64]。您可以阅读有关 GAC 的更多信息on the MSDN
  • 感谢您的反馈:)。
  • @JosuéZatarain 如果您打开默认 Visual Studio 项目模板并查看解决方案资源管理器中的 References 文件夹(包括我放置的 System在答案中)。你可能想看看你是否需要其他人:)
【解决方案2】:

您是否尝试过添加对“System.dll”和“System.ComponentModel.DataAnnotations.dll”的引用(对于 System.ComponentModel 的东西)? (因为您可能确实缺少程序集参考)

options.ReferencedAssemblies.Add(
    Path.Combine(
  Directory.GetCurrentDirectory(),
    "System.ComponentModel.DataAnnotations.dll"));

【讨论】:

  • 是的,我的回答可能还不够漂亮! :-)
猜你喜欢
  • 2016-07-31
  • 2019-08-29
  • 2013-07-07
  • 1970-01-01
  • 2016-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多