开发者

How to refer to enum values inside nhibernate formula mapping specification?

开发者 https://www.devze.com 2022-12-23 05:47 出处:网络
I have two entities types: RunContainer parent entity type Run child entity type Run has a property Status, which is of type RunStatus, like so:

I have two entities types:

  • RunContainer parent entity type
  • Run child entity type

Run has a property Status, which is of type RunStatus, like so:

public enum RunStatus
{
  Created,
  Starting,
  // ...
}
public class Run
{
  public int ContainerId { get; private set; }
  // ...
  public RunStatus Status { get; private set; }
}

RunContainer has a calculated property ActiveRunCount, like so:

public class RunContainer
{
  public int Id { get; private set; }
  // ...
  public int ActiveRunCount { get; private set; }
}

In the mapping for the RunContainer.ActiveRunCount property, I use the formula specification like so:

<property name="ActiveRunCount" formula="(select count(r.Id) from Run r where r.ContainerId = Id and r.Status = 1)"/>

My problem is that I refer to the RunStatus enum values in the formula by their 开发者_JS百科respective numeric value, rather than the appropriate symbolic name. Can anyone tell me how can I use the symbolic name instead?

Thanks.


NHibernate maps enums to the string representation if the SQL column is a string type, and this is the default if you let NHibernate generate the schema.

so:

ALTER TABLE Run ALTER COLUMN Status varchar(20)

and in the mapping

<class name="Run">
  <!- [...] -->
  <property name="Status"/>
</class>

Now the SQL table will contain a string representation of the enum. The formula can now query for it:

<property name="ActiveRunCount" formula="
  (select count(r.Id) from Run r 
  where r.ContainerId=Id and r.Status='Active')"/>

(If you already have data in the tables, you should write a conversion instead of the bare ALTER COLUMN statement).


EDIT after comment:

To generate the mapping file and make sure you have the enum value in the formula right, you could use FluentNhibernate. The mapping for the ActiveRun property would look like this:

Map(x => x.ActiveRunCount)
 .Formula(string.Format("(select count(r.Id) [...] and r.Status='{0}')",
   RunStatus.Active))

If that is what you were looking for, you could also keep the integers in the columns and do this:

Map(x => x.ActiveRunCount)
 .Formula(string.Format("(select count(r.Id) [...] and r.Status={0})",
   (int)RunStatus.Active))
0

精彩评论

暂无评论...
验证码 换一张
取 消