编程语言
首页 > 编程语言> > C#-ServiceStack ORMLite保存嵌套[参考]

C#-ServiceStack ORMLite保存嵌套[参考]

作者:互联网

是否可以使用ORMLite v4 for ServiceStack自动保存具有嵌套[Reference]属性的对象?例如:

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

我希望能够做到这一点…

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

…并将其写入所有三个表.就目前而言,我能想到的最好的事情是在保存顶级对象之后添加此内容(“ references:true”确实保存了嵌套的引用的第一层-也就是说,保险表已正确填充):

foreach(Insurance insurance in patient.Insurances)
{
    dbConn.SaveAllReferences(insurance);
}

依靠[参考]表存储和关联数据的深层嵌套JSON结构可能会很麻烦.有没有更好的办法?

谢谢!

解决方法:

不支持在多嵌套结构上保存引用,但是您可能会试图将大型JSON层次结构文档转换为可能会爆炸成多个表的关系结构而遇到麻烦.

较少摩擦的解决方案是仅使OrmLite将嵌套的复杂类型保存为无模式的文本Blob,对于非聚合的根数据(即,附加到在其父实体的上下文之外没有任何意义的实体的元数据)应考虑使用不需要在服务器端查询.

OrmLite对透明类型的透明化具有透明的支持,基本上只需删除嵌套表上的[Reference]属性即可.

否则,如果要将它们另存为单独的表,则可以采用正确的方法,在遵循更实用的样式时,可以将其浓缩为1-liner,例如:

patient.Insurances.Each(db.SaveAllReferences);

标签:servicestack,ormlite-servicestack,c,net
来源: https://codeday.me/bug/20191121/2054161.html