Nhibernate类映射将“_id”附加到列名

时间:2016-04-07 06:23:14

标签: c# nhibernate

我的数据库问题和语言代码

中有两个表

以下是问题表的结构:

QuestionId int
Text varchar(100)
LanguageCode uniqueidentifier

以下是 LanguageCode 表的结构:

Id uniqueidentifier
Name varchar(20)

现在我想使用NHibernate映射这两个实体,因为我创建了问题& LanguageCode实体:

问题实体:

public class Question
{
    public Question()
    {           
    }
    public virtual int Id { get; set; }

    public virtual string Text { get; set; }

    public  virtual LanguageCode LanguageCode { get; set; }
}

LanguageCode实体:

public class LanguageCode
{
    public LanguageCode()
    {

    }
    public virtual  Guid Id { get; set; }

    public virtual  string Name { get; set; }
}

以下是这两个实体类的映射

问号地图:

internal class QuestionMap : ClassMap<Question>
{
    public QuestionMap()
    {
        ReadOnly();
        Table("Question");
        Id(x => x.Id).Column("Id").GeneratedBy.Assigned();
        Map(x => x.Text);
        HasOne(x => x.LanguageCode);
    }
}

LanguageCode Map

internal class LanguageCodeMap:ClassMap<LanguageCode>
{
    public LanguageCodeMap()
    {
        ReadOnly();
        Table("LanguageCode");
        Id(x => x.Id).Column("Id").GeneratedBy.Assigned();
        Map(x => x.Name);
    }
}

现在执行以下代码:

LanguageCode languageCodeAlias = null;
Question question = null;
var res = session.QueryOver(()=>question)
                               .JoinAlias(() => question.LanguageCode, () => languageCodeAlias)

.WhereRestrictionOn(x=>x.Id).IsIn(questionIds).List();

我得到一个SQLException,下面是在执行时创建的查询:

 SELECT this_.Id as Id1_1_, this_.Text as Text2_1_1_,
 this_.LanguageCode_id as Language5_1_1_,
 languageco1_.Id as Id0_0_, languageco1_.Name as Name0_0_ FROM
 [Question] this_ inner join [LanguageCode] languageco1_ on
 this_.LanguageCode_id=languageco1_.Id WHERE this_.Id in (157827)

可以清楚地看到,使用 LanguageCode_id 而不是表名 LanguageCode ,我不知道如何解决这个问题。 所以请帮我解决这个问题,如果需要更多细节,请告诉我。

2 个答案:

答案 0 :(得分:1)

而不是HasOne我会使用proper reference

internal class QuestionMap: ClassMap<Question>
{
    public QuestionMap()
    {
        ReadOnly();
        Table("Question");
        Id(x => x.Id).Column("Id").GeneratedBy.Assigned();
        Map(x => x.Text);
        References(x => x.LanguageCode).Column("LanguageCode");
    }
}

HasOne适用于one-to-one special cases,我希望您使用相同的LanguageCode有很多问题。

答案 1 :(得分:0)

我通过添加以下类来找出解决方案:

public class CustomForeignKeyConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        instance.Column(instance.Class.Name);
    }
}

并在SessionFactory中配置:

Fluently.Configure()
             .Database(ConfigureDb())
             .Mappings(m=>m.AutoMappings.Add(AutoMap.AssemblyOf<QuestionMap>(cfg)
             .Conventions.AddFromAssemblyOf<CustomForeignKeyConvention>()))
             .BuildSessionFactory();

如果列名是&#34; columnname_abc&#34;然后我们可以改变

  

instance.Column(instance.Class.Name)到instance.Column(instance.Class.Name +&#34; _abc&#34;);