0

What I'm trying to achieve is generate a project dynamically from c# classes generated by me. This classes' content are a similar content of code-first code generation of entity framework.The content looks as follows:

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; }
    }
}

I generate this files from the tables in my database, and then try to compile it programmatically so that I can reference the generated project in another project that works with an API.

The main errors while compiling is:

The type or namespace name 'KeyAttribute' does not exist in the namespace 'System.ComponentModel.DataAnnotations' (are you missing an assembly reference?)

The type or namespace 'Key' could not be found

The type or namespace 'Table' could not be found.

I'm using 'CSharpCodeProvider'

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

And I have the following referenced Assemblies

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

I have an string array with the files' paths called sources, and I try to compile with the following line

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

Help is much appreciated.

4

2 回答 2

0

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

options.ReferencedAssemblies.Add(
    Path.Combine(
  Directory.GetCurrentDirectory(),
    "System.ComponentModel.DataAnnotations.dll"));
于 2016-04-22T14:38:02.257 回答
0

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

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

可能需要其他人

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

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

using System.ComponentModel.DataAnnotations.KeyAttribute;

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

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

于 2016-04-22T14:26:23.927 回答