0
我正在處理一個C#項目,從而在運行時從給定服務器上的給定數據庫動態構建ORM解決方案的映射,即nHibernate。目前,我正致力於獲取基本對象和關係映射類運行時生成工作。我能夠通過CodeDOM的內存編譯在運行時下面的類:在運行時從運行時生成的另一個對象生成的調用類
namespace DataDictionary.Domain
{
public class Entity
{
public virtual int EntityID { get; set; }
public virtual string EntityName { get; set; }
public virtual DateTime EntityFoundationDate { get; set; }
}
}
然而,當我嘗試使用的CodeDOM編譯下面的類相當於:
using System;
using System.Linq;
using NHibernate.Cfg;
using NHibernate.Cfg.MappingSchema;
...
namespace DataDictionary.Domain
{
public class EntityMap : ClassMapping<Entity>
{
public EntityMap()
{
this.Table(Entity);
this.ID(p => p.EntityID);
this.Property(p => p.EntityName);
this.Property(p => p.EntityFoundationDate);
}
}
}
我得到的編譯時以下錯誤:error CS0246: The type or namespace name 'Entity' could not be found (are you missing a using directive or an assembly reference?)
我的問題是爲什麼Entity
,儘管被放置在運行時編譯正確的命名空間,沒有被看到。
此外,僅供參考,這裏是我用來創建EntityMap
方法:
public static object CreateNewObject(ref object table, AssemblyName domain, params FieldInfo[] columns)
{
if (columns == null || columns.Length == 0)
return null;
string tableName = table.GetType().Name;
//check to see if a class exists which both matches the name of `table`
//and whose full name contains the correct assembly to be used.
var namespaceCheck = (from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetTypes()
where type.Name == tableName && Utilities.GetFriendlyAssemblyName(type.FullName).Equals("DataDictionary.Domain")
select type).FirstOrDefault();
if (namespaceCheck == null)
throw new InvalidOperationException("Valid type not found.");
StringBuilder builder = new StringBuilder("using NHibernate; using NHibernate.Cfg; using NHibernate.Cfg.MappingSchema; using NHibernate.Dialect; using NHibernate.Mapping.ByCode; using NHibernate.Mapping.ByCode.Conformist; ");
builder.Append("namespace DataDictionary.Domain{");
builder.AppendFormat("public class {0}Map : ClassMapping<{0}> {{", tableName);
builder.AppendFormat("public {0}Map(){{\n",tableName);
builder.AppendFormat("this.Table({0});", tableName);
//find the ID column.
var list = columns.Where(x => x.Name.ToUpper().Contains("ID"));
builder.AppendFormat("this.ID(p => p.{0})", Utilities.cleanFieldName(list.ElementAt(0).Name));
columns = columns.Where(x => !x.Equals(list.ElementAt(0))).ToArray();
//map the properties.
foreach (FieldInfo column in columns)
{
builder.AppendFormat("this.Property(p => p.{0});", Utilities.cleanFieldName(column.Name));
}
//close all open brackets.
builder.Append("}}}");
//send code to helper class for runtime compilation via CodeDOM.
return CodeDOM_Helpers.Execute(builder.ToString(), tableName,domain.Name);
}
固定在OP中;感謝您指出了這一點! – Expack3
另外,想補充一點,這並沒有解決我的問題,因爲我仍然得到相同的錯誤。 (這是有道理的,因爲它是映射類中的一個錯字,當映射類實際上看到對象類時它會觸發。) – Expack3