RobertMGlynn
RobertMGlynn

Reputation: 505

How to update nested objects in NPoco

I can't find an example of updating a nested object in a many-to-one situation. It's pretty clear how the mapping works on a Fetch; and I'm not speaking of updating a collection of nested objects, just one. So given the following example:

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }
    [ResultColumn]
    public School CurrentSchool { get; set; }
}

public class School
{
    public int SchoolId { get; set; }
    public string Name { get; set; }
}

In the database, the Student table carries a CurrentSchool column that is the ID of a record in the School table.

I'm not updating the School object itself, rather mapping the student to a different one. This is fine on a Query, but if I change the CurrentSchool object on the Student and save with db.Update(studentObject), the foreign key doesn't update.

Upvotes: 1

Views: 2394

Answers (1)

RobertMGlynn
RobertMGlynn

Reputation: 505

After stepping through the source, I found there was a ReferenceType property on the NPoco.ColumnInfo class. Searching for this, lo and behold there is documentation in the NPoco wiki down under Version 3 -> Relationships (https://github.com/schotime/NPoco/wiki/Version-3#relationships).

If I add in:

[NPoco.Reference(NPoco.ReferenceType.Foreign, ColumnName = "SchoolId", ReferenceMemberName = "SchoolId")]
public School CurrentSchool { get; set; }

then the foreign-key relationship is saved when the Student object is persisted in the DB.

Upvotes: 1

Related Questions