在运行时编译代码优先的EF4类时遇到问题:)

时间:2012-04-27 14:33:56

标签: c# c#-4.0 compilation runtime

我尝试在运行时编译此代码。这段代码是代码优先的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?)}

任何帮助?

谢谢。

2 个答案:

答案 0 :(得分: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");

除此之外,请确保在要编译的代码中使用以下命名空间:using System.Data.Entity; using System.Collections.Generic; using System.ComponentModel.DataAnnotations;这应解决有关此问题的编译问题。

答案 1 :(得分:0)

我也遇到了这个问题,并将网站从.NET 4.0升级到.NET 4.6.1,它已修复。请记住删除NUGET组件并重新安装新的.NET目标新版本。

相关问题