1

実行時にこのコードをコンパイルしようとしています。このコードは、コード ファーストの EF4 クラスです。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;

namespace EFCodeFirst.Model.Models
{
    [Table("Blog")]
    public class Blog
    {
        public Guid Id { get; set; }
        [Column("txtTitle")]
        public string Title { get; set; }
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public string ShortTitle { get { return Title; } }
        public string BloggerName { get; set; }
        public virtual ICollection<Post> Posts { get; set; }
    }

    public class Post
    {
        public Guid Id { get; set; }
        public string Title { get; set; }
        public DateTime DateCreated { get; set; }
        public string Content { get; set; }
        public Guid BlogId { get; set; }
    }
}

このメソッドを使用して、指定されたコードをコンパイルします。このコードを単純なクラスでテストしました。できます。しかし、特定のクラスでは、まったく機能しません。

private Assembly BuildAssembly(string code)
        {
            Microsoft.CSharp.CSharpCodeProvider provider = new CSharpCodeProvider();
            ICodeCompiler compiler = provider.CreateCompiler();
            CompilerParameters compilerparams = new CompilerParameters();
            compilerparams.GenerateExecutable = false;
            compilerparams.GenerateInMemory = true;
            CompilerResults results = compiler.CompileAssemblyFromSource(compilerparams, code);
            if (results.Errors.HasErrors)
            {
                StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
                foreach (CompilerError error in results.Errors)
                {
                    errors.AppendFormat("Line {0},{1}\t: {2}\n", error.Line, error.Column, error.ErrorText);
                }
                throw new Exception(errors.ToString());
            }
            else
            {
                return results.CompiledAssembly;
            }
        }

そして、私は次のようないくつかの例外を取得しています:

error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)}

何か助けはありますか?

ありがとうございました。

4

2 に答える 2

0

「compilerparams」に ReferencedAssemblies が設定されていないようです。ほとんどの場合、通常の VS C# プロジェクトに追加する場合と同様に、必要なアセンブリ参照を追加する必要があります。次のようなものを使用して BuildAssembly メソッドに追加してみてください。

compilerparams.ReferencedAssemblies.Add("mscorlib.dll"); compilerparams.ReferencedAssemblies.Add("System.dll"); compilerparams.ReferencedAssemblies.Add("System.Core.dll"); compilerparams.ReferencedAssemblies.Add("System.Xml.dll"); compilerparams.ReferencedAssemblies.Add("EntityFramework.dll");

これに加えて、コンパイルするコードに次の名前空間 usings があることを確認してください。using System.Data.Entity; using System.Collections.Generic; using System.ComponentModel.DataAnnotations;これにより、この問題に関するコンパイルの問題が解決されるはずです。

于 2012-04-27T14:43:19.913 に答える
0

私もこの問題に遭遇し、Web サイトを NET 4.0 から NET 4.6.1 にアップグレードしたところ、修正されました。NUGET コンポーネントを削除し、新しい NET ターゲットの新しいバージョンに再インストールすることを忘れないでください。

于 2016-03-14T09:11:09.937 に答える