سؤال

If this is the way for hard-coded mapping for nullable and not nullable database fields

// nullable
Map(x => x.FirstName)
  .Nullable();

// not nullable
Map(x => x.FirstName)
  .Not.Nullable();

How is it done with automapping and conventions?

Also, it is not obvious but the purpose that I need it for is to have nhibernate generate insert sql statements without using a primary key field.

Example: if I want database to generate ProductId, instead of

insert into Product (ProductId, Name) values (1, 'product name');

NHibernate should generate

insert into Product (Name) values ('product name');

And, rdbms should not be a question here, as a client code should not care how database assigns it.

هل كانت مفيدة؟

المحلول

After all, solution is in implementing IIdConvention interface. I'm adding some code in case someone find this useful.

public class PrimaryKeyConvention : IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {            
        instance.Column(instance.EntityType.Name + "Id");
        instance.GeneratedBy.Native();
    }
}

It can even be used with custom class for generating id

public class PrimaryKeyConvention : FluentNHibernate.Conventions.IIdConvention
{
    public void Apply(IIdentityInstance instance)
    {            
        instance.Column(instance.EntityType.Name + "Id");
        instance.GeneratedBy.Custom(typeof(CustomIdGenerator));
    }
}
public class CustomIdGenerator : NHibernate.Id.IIdentifierGenerator
{

    public object Generate(NHibernate.Engine.ISessionImplementor session, object obj)
    {
        return null; //this should be custom implemented
    }
}

نصائح أخرى

Setting the responsability to generate the primary key to database, using fluent nhibernate doesnt solve your problem ?

public class ProductMap : ClassMap<Product>
{
    public ProductMap()
    {
        Id(x => x.Id).GeneratedBy.Native();

        Map(x => x.Name).Nullable();
        ...
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top