2

I have these tables/classes (example):

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; }
}

The mapping is:

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 can have (0,1) SecondClass, and SecondClass can have (1,1) FirstClass.

The bellow code return the error "attempted to assign id from null one-to-one property: 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.
2
  • Does it work when you invert the instantiation? first instantiate FirstClass and then assign a new SecondClass to it. Commented Jun 6, 2011 at 22:01
  • Hi @Variant, I tried, but didn't work. Tks. Commented Jun 6, 2011 at 23:24

1 Answer 1

2

It seems like NH is trying to save SecondClass first and fails to grab a generated ID from the not yet saved FirstClass.

Try to move the .Cascade.SaveUpdate() to the References declaration in FirstClassMap and call the save command on FirstClass.

Sign up to request clarification or add additional context in comments.

1 Comment

This works, tks, I save the FirstClass with SecondClass null, after I set SecondClass in FirstClass and save. Tks. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.