fluent nHibernate: How to persist a property which is mapped with Formula?

自闭症网瘾萝莉.ら 提交于 2019-12-24 10:31:06

问题


I am dealing with a legacy database, and we have a field which doesn't make sense anymore, but I would rather not change the DB schema.

I'm trying to map an old DB text field into a class with a boolean (only need to know about one option that the DB text field has). I can get the boolean value out of the DB using Forumla, but I can seem to get it to save any updates back into the DB.

My class and current fluent mapping for it is:

public class Bulletin
{
    public virtual int Id { get; set;}
    public virtual bool RegularBulletin { get; set;}
}

public class BulletinMapping : ClassMap<Bulletin>
{
    public BulletinMapping()
    {
        Table("Bulletins");
        Id(x => x.Id, "ID").GeneratedBy.Identity();

        Map(x => x.RegularBulletin)
            .Formula("case when EmailType = 'BULLETIN_B' then 1 else null end")
            .Nullable();
    }
}

Does anyone have any ideas about how to persist the RegularBulletin field?

Thanks Saan


回答1:


I would use a workaround for this- create a backing field protected virtual string RegularBulletinString and use your boolean conversion formula on it.

public class Bulletin
{
    public virtual int Id { get; set;}
    protected virtual string RegularBulletinString { get; set;}
    public virtual bool RegularBulletin 
    { 
       get
       {
          return RegularBulletinString == "BULLETIN_B";
       } 
       set
       {
          RegularBulletinString = value? "BULLETIN_B" : null;
       }
    }
}

public class BulletinMapping : ClassMap<Bulletin>
{
    public BulletinMapping()
    {
        Table("Bulletins");
        Id(x => x.Id, "ID").GeneratedBy.Identity();

        Map(x => x.RegularBulletinString)
            .Column("EmailType")
            .Nullable();
        IgnoreProperty(x=> x.RegularBulletin); 

    }
}


来源:https://stackoverflow.com/questions/7205341/fluent-nhibernate-how-to-persist-a-property-which-is-mapped-with-formula

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!