Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can refine this solution to make it more reusable. As I understand, you don't like mapping duplication. This can be avoided:</p> <p>I have created a SuperModelMapHelper class that contains an extension method:</p> <pre><code>public static class SuperModelMapHelper { public static void MapSuperModel&lt;T&gt;(this ClassMap&lt;T&gt; classMap) where T : SuperModel { classMap.WithTable("SuperModels"); classMap.Id(x =&gt; x.Id); classMap.Map(x =&gt; x.FirstName); } } </code></pre> <p>As you can see - it's generic and will accept any of SuperModel's subclasses. Then, there are two mappings:</p> <pre><code>public class SuperModelMap : ClassMap&lt;SuperModel&gt; { public SuperModelMap() { MapSuperModel(); } } public class SubModelMap : ClassMap&lt;SubModel&gt; { public SubModelMap() { MapSuperModel(); } } </code></pre> <p>I've used extension method to preserve convention of FluentNHibernate, you can make it simple static method and pass class map as a parameter.</p> <p>And this code:</p> <pre><code>Guid id; using (var session = sf.OpenSession()) using (var transaction = session.BeginTransaction()) { var subModel = new SubModel() {FavoriteColor = "blue", FirstName = "Jane"}; session.Save(subModel); id = subModel.Id; transaction.Commit(); } using (var session = sf.OpenSession()) using (var transaction = session.BeginTransaction()) { var superModel = session.Get&lt;SuperModel&gt;(id); Console.WriteLine(superModel.GetType().Name); Console.WriteLine(superModel.FirstName); transaction.Commit(); } </code></pre> <p>Works as intended - type is SuperClass. Note that I've created second session. You'd have to flush your session before trying to load entity in the same session you saved it, because NHibernate defers query execution. </p> <p>Using this solution there is very little duplication. You can investigate AutoMapping feature of FluentNHibernate to reduce it even more - perhaps creating own convention would let you to automatically map such classes.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload