I have seen a few questions like this on SO, but I still cannot get this to work in my code, despite my code looking like the accepted answers.
First, my mapping (condensed)
public SiteMap()
{
Table("SiteDetail");
Id(x => x.SiteId, "Id").GeneratedBy.Identity();
}
Then, the other table's structure
CREATE TABLE [dbo].[EmailConfig](
[SiteID] [int] NOT NULL,
[Active] [int] NULL,
[HeaderText] [int] NULL,
[TrailerText] [int] NULL,
[BodyText] [int] NULL,
[CopyEmailTo] [varchar](255) NULL,
CONSTRAINT [PK_EmailConfig] PRIMARY KEY CLUSTERED ([SiteID] ASC))
And here is my property in my object
public virtual bool EmailReceiptsEnabled { get; set; }
And here is the mapping to set this property
Map(x => x.EmailReceiptsEnabled)
.Formula("(SELECT COUNT(e.SiteId) FROM EmailConfig e WHERE e.SiteId = SiteId AND e.Active = 1)");
When I comment out that property mapping, everything works fine. When I leave it in, my repository returns null when trying to select a single site. No error is thrown, other than the null reference exception on the page trying to access a property of the site object.
EDIT:
I have modified my solution to pull back an object like so:
public class EmailConfiguration : CoreObjectBase
{
public virtual int SiteId { get; set; }
public virtual int Active { get; set; }
}
With a property in my Site
class
public virtual EmailConfiguration EmailConfiguration { get; set; }
And the mapping for the object
public class EmailConfigurationMap : ClassMap<EmailConfiguration>
{
public EmailConfigurationMap()
{
Table("EmailConfig");
Id(x => x.SiteId);
Map(x => x.Active);
}
}
And then the mapping in my site
References(x => x.EmailConfiguration, "Id");
And it produces an error
NHibernate.ObjectNotFoundException: No row with the given identifier exists
The issue is that EmailConfig contains no record until the client goes in to the app to configure their Email. That can't be changed, but I need my application to be able to use this data. Any ideas on how to map this thing?
Yet another edit
I was able to get it to work by changing the property to this
public virtual IList<EmailConfiguration> EmailConfigurations { get; set; }
And then implementing this complete disaster
HasMany<EmailConfiguration>(x => x.EmailConfigurations)
.KeyColumn("SiteId")
.Inverse();
I think I'll go cry quietly until I can figure out how to make this mess work the right way. Since the EmailConfig
table uses the PK of my site table as its primary key, the only possibilities are to have 1 or no records. References
fails on null with a hard error. HasOne doesn't work either (causes the program to not pull back my Site
objects at all without any errors).