我有这些表/类(示例):

table FirstTable (
    Id INTEGER NOT NULL DEFAULT AUTOINCREMENT,
    Name VARCHAR(100) NOT NULL,
    Document VARCHAR(20) NOT NULL
)

table SecondTable (
    Id INTEGER NOT NULL,
    Something VARCHAR(100) NULL,
    FOREIGN KEY (Id) REFERENCES FirstTable (Id)
)

public class FirstClass {
    public string Name { get; set; }
    public string Document { get; set; }
    public SecondClass SecondClass { get; set; }
}

public class SecondClass {
    public string Something { get; set; }
    public FirstClass FirstClass { get; set; }
}


映射为:

public class FirstClassMap : ClassMap<FirtsClass> {
    Table("FirstTable");
    Id(x => x.Id).GeneratedBy.Identity();
    Map(x => x.Name);
    Map(x => x.Document);
    References(x => x.SecondClass, "Id").ForeignKey();
}

public class SecondClassMap : ClassMap<SecondClass> {
    Table("SecondTable");
    Id(x => x.Id).GeneratedBy.Foreign("FirstClass");
    Max(x => x.Something);
    HasOne(x => x.FirstClass).PropertyRef(x => x.SecondClass).Cascade.SaveUpdate();
}


FirstClass可以具有(0,1)SecondClass,而SecondClass可以具有(1,1)FirstClass。

下面的代码返回错误“试图从空的一对一属性分配ID:SecondClass”

var test = new SecondClass();
test.FirstClass = new FirstClass();

test.Something = "New test";
test.FirstClass.Name = "My name";
test.FirstClass.Document = "My document";
// ... commands to save.

最佳答案

看来NH正在尝试先保存SecondClass,但无法从尚未保存的FirstClass中获取生成的ID。

尝试将.Cascade.SaveUpdate()移到References中的FirstClassMap声明,然后在FirstClass上调用save命令。

关于c# - 流利的nHibernate映射问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6257124/

10-13 03:18