NHibernate 3.3.1 explicit polymorphism

I am using NH 3.3.1. Suppose simple classes:

public class TestBase { public virtual int Id { get; set; } public virtual string A { get; set; } } public class Test : TestBase { public virtual string B { get; set; } } 

and displays for them:

 public sealed class TestBaseMap : ClassMap<TestBase> { public TestBaseMap() { this.Polymorphism.Explicit(); this.Id(a => a.Id).GeneratedBy.Identity(); this.Map(a => aA); } } public sealed class TestMap :SubclassMap<Test> { public TestMap() { this.Map(a => aB); } } 

Even with the specified Polymorphism.Explicit (), NH still remains a Test connection when requested for TestBase.

 var a = this.Session.Get<TestBase>(1); 

I do not need this join because it will have many subclasses. I checked the xml generated freely. this is normal, there is an "explicit" sentence. What am I doing wrong?

+4
source share
2 answers

I assume that explicit polymorphism is used only in queries, not session.Get. But I could not find references to this.


Try not to query the base class, but always have a specific subclass (which in most cases is the best design):

 public abstract class TestBase { public virtual int Id { get; set; } public virtual string A { get; set; } } public class TestA : TestBase { public virtual string B { get; set; } } public class TestB : TestBase { public virtual string B { get; set; } } var a = this.Session.Get<TestA>(1); 
+2
source

Ok I understood. As Stefan suggested, I created an abstract test base. But since I really needed to query the TestBase table without many left joins, I introduced a stub class:

 public class TestStub : TestBase { // nothing } 

This class is completely empty. Map:

 public sealed class TestStubMap : SubclassMap<TestStub> { public TestStubMap() { this.Table("TestBase"); this.KeyColumn("Id"); } } 

Now I can request:

 var a = this.Session.Get<TestStub>(1) 

It produces only one connection (TestBase join TestBase). So, now I can get my test base from db without overhead. I do not like hacks, but if the built-in logic does not work (polymorphism = explicit), what remains to be done.

+2
source

Source: https://habr.com/ru/post/1433984/


All Articles