簡體   English   中英

FluentNhibernate自定義主鍵自動映射 - (dis)允許空值

[英]FluentNhibernate Custom Primary key Automapping - (dis)allow nulls

如果這是可空和不可空數據庫字段的硬編碼映射的方式

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

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

它是如何通過自動化和約定完成的?

此外,它並不明顯,但我需要它的目的是讓nhibernate生成insert sql語句而不使用主鍵字段。

示例:如果我希望數據庫生成ProductId,而不是

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

NHibernate應該生成

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

並且,rdbms不應該是一個問題,因為客戶端代碼不應該關心數據庫如何分配它。

畢竟,解決方案是實現IIdConvention接口。 我正在添加一些代碼以防有人發現這個有用。

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

它甚至可以與自定義類一起用於生成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
    }
}

設置責任以生成數據庫的主鍵,使用流暢的nhibernate不能解決您的問題?

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

        Map(x => x.Name).Nullable();
        ...
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM