Reputation: 581
Is it possible to automatically save an object with nested [Reference] properties using ORMLite v4 for ServiceStack? For example:
public class Patient
{
[PrimaryKey]
public int Id { get; set; }
public string Name { get; set; }
[Reference]
public List<Insurance> Insurances { get; set; }
}
public class Insurance
{
[PrimaryKey]
public int Id { get; set; }
[ForeignKey(typeof(Patient))]
public int PatientId { get; set; }
public string InsuranceName { get; set; }
public string InsuranceLevel { get; set; }
[Reference]
public List<Contact> InsuranceContacts { get; set; }
}
public class Contact
{
[PrimaryKey]
public int Id { get; set; }
[ForeignKey(typeof(Insurance))]
public int InsuranceId { get; set; }
public string ContactName { get; set; }
}
I would love to be able to do this...
var patient = new Patient
{
Name = "Nathan",
Insurances = new List<Insurance>
{
new Insurance
{
InsuranceName = "Aetna",
InsuranceLevel = "Primary",
InsuranceContacts = new List<Contact>
{
new Contact
{
ContactName = "Bob"
}
}
},
new Insurance
{
InsuranceName = "BCBS",
InsuranceLevel = "Secondary",
InsuranceContacts = new List<Contact>
{
new Contact
{
ContactName = "Susan"
}
}
}
}
}
db.Save(patient, references:true);
...and have it write to all three tables. As it stands, the best thing I can come up with is to add this after saving the top-level object (the "references:true" does save the first nested level of references - that is, the Insurance table is properly filled):
foreach(Insurance insurance in patient.Insurances)
{
dbConn.SaveAllReferences(insurance);
}
This can get painstaking with deeply nested JSON structures that rely on [Reference] tables to store and relate data. Is there a better way?
Thanks!
Upvotes: 3
Views: 2238
Reputation: 143389
Saving references on multi-nested structures isn't supported, but you're likely headed towards friction trying to convert a large JSON hierarchical document to a relational structure which has the potential to explode into multiple tables.
A solution with less-friction is to just let OrmLite save nested complex types as schema-less text blobs which should be considered for non-aggregate root data, i.e. metadata attached to entities that don't make sense outside the context of its parent entity and that doesn't need to be queried server-side.
OrmLite has transparent support for blobbing complex types, basically just by removing the [Reference]
attributes on the nested tables.
Otherwise if you want to save them as in separate tables you have the right approach which can be condensed into a 1-liner when following a more functional style, e.g:
patient.Insurances.Each(db.SaveAllReferences);
Upvotes: 3