简体   繁体   中英

NHibernate Mapping a property to the existence of a row

I have the following entity and Fluent NHibernate mapping:

public class Advertiser
{
    public virtual int AdvertiserId { get; set; }
    public virtual string AdvertiserName { get; set; }
    public virtual bool IsPriorityEntity { get; set; }
}

public class AdvertiserMapping : ClassMap<Advertiser>
{
    public AdvertiserMapping()
    {
        Id(a => a.AdvertiserId).GeneratedBy.Identity();
        Map(a => a.AdvertiserName);
    }
}

The IsPriorityEntity property is stored in the database by the existence of a row in the PriorityEntity Table.
The query looks something like:

Select 
  AdvertiserId, 
  AdvertiserName,  
  CASE WHEN pe.PriorityEntityID IS NOT NULL 
       THEN 1 
       ELSE 0 END as IsPriorityEntity  
From Advertisers adv  
  Left Join PriorityEntity pe 
    on pe.PriorityEntityID = adv.AdvertiserID 
      and pe.EntityTypeID = 6

I am at a loss as to how to map something like this.

You could make it object oriented and map the whole stuff:

public class Advertiser
{
    public virtual int AdvertiserId { get; set; }
    public virtual string AdvertiserName { get; set; }
    public virtual bool IsPriorityEntity { get { return Priority != null; } }
    public PriorityEntity Priority { get; set; }
}

Or you write custom sql for loading the whole entity or the singe property:

(sorry, I don't use fluent, this is the xml mapping)

<property 
  name="IsPriorityEntity" 
  formula="Select CASE WHEN count(pe.PriorityEntityID) = 0 THEN 0 ELSE 1 END From PriorityEntity pe WHERE pe.PriorityEntityID = AdvertiserID"/>

You can't update the property directly here. You could probably also write custom sql to update and insert, but I think this will become complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM