Fluent NHibernate - is it possible to map property to persistent computed column in Sql server

I want to map a readonly property to a computed column in Sql Server using Fluent NHibernate. A property is a substring of another. I do this to make the substring indexable and have better search performance. But when I use the Formula function in a mapping, the property is not mapped to the computed column in the database, but computed when using the query.

Class Person{
   public virtual string name {get; set;}
   public virtual string subName {get; set;}
}

Class PersonMap : ClassMap<Person>{
   Map(p => p.name);
   Map(p => p.subName).Generated.Always().Formula("substring(name, 0, 5)");
}

      

+3


source to share


1 answer


You need to copy the functionality of your code - if you change the name property, NHibernate will not by default send a new query to the database to evaluate the generated properties.

You need to do something like:

 public virtual string subName { get { return name.Substring(0, 5); } set { } }

      



Note that you need an empty setter, otherwise NHibernate will complain

Edit: I see that you want to index a column in the database, so you will need to create a computed column for that table in the database. This by itself has nothing to do with NHibernate, and you can either ignore the column entirely in your mapping (as long as you copy it in your code) or discard the .Formula (..) part (since this is stated in the computed column already)

+3


source







All Articles