使用流利的nhibernate映射对象

时间:2015-10-23 12:35:16

标签: c# .net nhibernate

public abstract class BaseEntity
 {
        public virtual int Id { get; set; }
}

public class MyClass : BaseEntity
{
    public virtual Language Language { get; set; }  
}

public class Language : BaseEntity
{          
        public virtual string Name { get; set; }
 }

映射

public class MyClassMap : BaseEntityMap<MyClass>
 {
        public MyClassMap()
            : base()
        {
            this.Table("MyClass");     
            this.References(x => x.Language).Column("Id");
        }
 }

 public class LanguageMap : BaseEntityMap<Language>
 {        
     public LanguageMap() : base()
     {
         this.Table("Language");
         this.Map(x => x.Name);
     }
 }

语言表的db表示 LanguageID名称 1英文 2德意志 ...

我在会话工厂内

    private ISessionFactory CreateSessionFactory()
    {
       return Fluently.Configure()                    .Database(MsSqlConfiguration.MsSql2012.ConnectionString(this.cnnString))
                    .Mappings(m => m.FluentMappings
                    .AddFromAssemblyOf<LanguageMap>()
                    .AddFromAssembly(this.entityAssembly)
                    .Conventions.Setup(x => 
                    { 
                        x.Add(ForeignKey.EndsWith("Id")); 
                    }))
                    .ExposeConfiguration(cfg => cfg.SetInterceptor(new GeneratedPropertiesInterceptor()))
                    .BuildSessionFactory();
   }

显然我当前的MyClassMap存在问题,因为我没有从db表中得到预期的结果

this.References(x => x.Language).Column("Id");

问题是:你如何在MyClassMap中映射语言属性?

1 个答案:

答案 0 :(得分:0)

你可以这样试试

public class LanguageMap : BaseEntityMap<Language>
{
    public LanguageMap(): base()
    {
        this.Table("Language");
        this.Map(x => x.Name);
        this.HasMany(x => x.MyClass)
                .Access.CamelCaseField(Prefix.Underscore)
                .Fetch.Select()
                .LazyLoad()
                .KeyColumns.Add("\"LanguageId\""); // database property name : LanguageId
    }
}
public class MyClassMap : BaseEntityMap<MyClass>
{
    public MyClassMap(): base()
    {
        this.Table("MyClass");
        this.References(x => x.Language).Column("LanguageId");
    }
}