fluent nhibernate PrimaryKeyConvention for propert

2019-08-29 21:10发布

问题:

This question has been asked already but there was no decent answer.

Is there a property name convention for fluent nhibernate so that instead of looking for Id it looks for ProductId ?

PrimaryKeyConvention applies to the column names in the database, NOT the property names.

Consider this scenario:

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
}

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool ShouldMap(Type type)
    {
        bool shouldMap = type.In(typeof(Product));
        return shouldMap;
    }
}

public void TestFluentNHibernate()
{
    var configuration = Fluently.Configure().
        Database(MsSqlConfiguration.MsSql2008.ConnectionString("database=asd;server=.\\sqlexpress;trusted_connection=true;"))
        .Mappings(m =>
                        {
                            IAutomappingConfiguration cfg = new AutomappingConfiguration();
                            m.AutoMappings.Add(AutoMap.AssemblyOf<Product>(cfg).Conventions.AddFromAssemblyOf<PrimaryKeyConvention>());
                        });

    var factory = configuration.BuildSessionFactory();
}

results in:

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

What convention can I add/override to tell fluent nhibernate to look for 'EntityName'+"Id" in the property names? I've looked at this convention page but havent found the one to override.

回答1:

public class AutomappingConfiguration : DefaultAutomappingConfiguration
{
    public override bool IsId(Member member)
    {
        return member.Name == member.DeclaringType.Name + "Id";
    }
}