NHibernate -将Oracle序列Map到非ID列

xwbd5t1u  于 2023-10-16  发布在  Oracle
关注(0)|答案(1)|浏览(85)

假设一个这样的表:
| ID| Foo|酒吧|
| --|--|--|
| NUMBER| VARCHAR2| NUMBER|
像这样的类:

public class SomeClass
{
    public virtual long Id {get;set;}
    public virtual string Foo {get;set;}
    public virtual long Bar {get;set;}
}

如何将BarMap到Sequence的值?它始终为NULL,尽管插入了其余数据。
我试着根据谷歌搜索:

public SomeTableMapping
{
    Schema("ABC");
    Table("SomeTable");

    // id sequence generator works fine
    Id(p => p.Id, map =>
      {
         map.Column("ID");
         map.Generator(Generators.Sequence, 
           gMap => gMap.Params(new {sequence = "MyID_SEQ"}));
      });

    Property(p => p.Foo, map => map.Column("FOO");

    // This doesn't work, but also doesn't error
    Property(p => p.Bar, map => map.Formula("SELECT ABC.Other_SEQ.nextval BAR FROM dual"));
}

更新
如果我将我的Map代码改为这样,它会在我的SomeClass示例上生成Bar的值,但不会在数据库中的记录上设置:

Property(p => p.Bar, map =>
    {
        map.Column("BAR");
        map.Formula("ABC.Other_SEQ.nextval");
        map.Generated(PropertyGeneration.Insert);
    }
k97glaaz

k97glaaz1#

Property(x => x.Bar, m =>
{
    m.Column("BAR");
    m.Generated(NHibernate.Mapping.ByCode.PropertyGeneration.Insert);
    m.Column(c => c.Default("ABC.Other_SEQ.nextval"));
});

这样就行了

var instance = new SomeClass { Foo =  "foo" };
session.Save(instance);
transaction.Commit();

var generatedValue = instance.Bar; // <- generated Value

session.Clear();
var loadedAgain = session.Get(instance.Id);
Assert.Equal(instance.Bar, loadedAgain.Bar);

相关问题