Michal Ciechan
Michal Ciechan

Reputation: 13888

Fluent NHibernate AutoMapping PrimaryKey Property Name is not "Id"

I am trying to migrate to Fluent NHibernate and have the following problem :(

I have a a number of classes called in the manner of CompanyXXXXXX, which all have a PrimaryKey of "CompanyId" which is of type Company.

A HBM Mapping file which i was using until name was this:

  <class name="CompanyAccounting" table="Company_Accounting" >
    <id column="CompanyID" type="Int32">
      <generator class="foreign">
        <param name="property">Company</param>
      </generator>
    </id>
    <one-to-one name="Company" constrained="true" />
  </class>

The entity is as follows:

public class CompanyAccounting
{
    public virtual Company Company {get;set;}        
}

Is it possible to use some sort of AutoMapping feature, as i have a dozen of these classes and there is likely to be more.

I have tried the following:

    public class CustomPrimaryKeyConvention : IIdConvention
    {
        public void Apply(IIdentityInstance instance)
        {
            var type = instance.EntityType;
            if (type.Name.StartsWith("Company") && type.Name.Length > 7)
            {
                instance.CustomType(typeof(Company));
                instance.Column("CompanyId");
            } 
            else
            {
                instance.Column(instance.EntityType.Name + "Id");
            }
        }
    }

EDIT : But my If(...)[For "CompanyAccounting" Type] doesn't even get hit. Any suggestions?

Exception:

The entity 'CompanyAccounting' doesn't have an Id mapped. 
Use the Id method to map your identity property. For example: Id(x => x.Id).

Upvotes: 1

Views: 1342

Answers (1)

Chris Marisic
Chris Marisic

Reputation: 33098

Did you register that convention with Fluent Nhibernate?

You should have something along the lines

AutoMap.AssemblyOf<CompanyAccounting>()
       .Conventions.AddFromAssemblyOf<CustomPrimaryKeyConvention>()

Upvotes: 1

Related Questions