我试图在运行时编译这段代码。此代码是代码优先的 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?)}
有什么帮助吗?
谢谢你。