Question

Basically I'm trying to figure out how to make a Fluent NHibernate mapping restrict itself to only hold one record for holding the application's configuration.

Here's the map in question:

class ConfigurationMap : ClassMap<Configuration>
{
    public ConfigurationMap()
    {
        Id(x => x.Id).Column("configurationId").GeneratedBy.Identity();
        Map(x => x.DefaultLocation);
        Map(x => x.DefaultPrinter);
        Map(x => x.DefaultPrinterLabelAmount);
        Map(x => x.DefaultCompanyName);
        Map(x => x.FolderLocalPath);
        Map(x => x.CompanyNameEnabled);
        Map(x => x.TimestampLabelEnabled);
        Map(x => x.CollectionFeeEnabled);
    }
}

I've seen this answer that fits my usecase: https://stackoverflow.com/a/3967446/273162

Basically I'm trying to figure out the Fluent NHibernate analogue to make it work like the answer in the link above.

Disclaimer: I've gone with an external config file before and decided that it's better/simpler to hold everything inside the database instead.

Was it helpful?

Solution

You can add the check constraint by adding CheckConstraint("configurationId = 1") to your ClassMap:

class ConfigurationMap : ClassMap<Configuration>
{
    public ConfigurationMap()
    {
        Id(x => x.Id).Column("configurationId").GeneratedBy.Identity();

        // Other properties

        CheckConstraint("configurationId = 1");
    }
}

This will result in the following SQL:

CREATE TABLE Configuration (
    configurationId INT IDENTITY NOT NULL,
    PRIMARY KEY (configurationId)
    CHECK (configurationId = 1)
)

which is pretty similar to the answer at https://stackoverflow.com/a/3967446/273162.

Once you've inserted a row in the table, the identity column will be 1 and the constraint will fail :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top