【问题标题】:ServiceStack ORMLite saving nested [Reference]ServiceStack ORMLite 保存嵌套 [参考]
【发布时间】:2014-05-11 07:05:54
【问题描述】:

是否可以使用 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);
}

这对于依赖 [Reference] 表来存储和关联数据的深层嵌套 JSON 结构可能会很麻烦。有没有更好的办法?

谢谢!

【问题讨论】:

    标签: c# .net servicestack ormlite-servicestack


    【解决方案1】:

    不支持在多嵌套结构上保存引用,但您可能会在尝试将大型 JSON 分层文档转换为可能爆发成多个表的关系结构时遇到摩擦。

    一种摩擦较小的解决方案是让 OrmLite 将嵌套的复杂类型保存为无架构的文本 blob,应考虑将其用于非聚合根数据,即附加到在上下文之外没有意义的实体的元数据它的父实体,不需要在服务器端查询。

    OrmLite 透明地支持 blobing 复杂类型,基本上只需删除嵌套表上的 [Reference] 属性。

    否则,如果您想将它们保存在单独的表格中,您有正确的方法可以在遵循更实用的样式时将其压缩为 1-liner,例如:

    patient.Insurances.Each(db.SaveAllReferences);
    

    【讨论】:

    • 感谢您的单行。我喜欢尽可能浓缩!是的,我对许多属性都使用了 blobing 方法,但是由于我们将对这些数据进行大量分析,因此其中大部分需要拆分到单独的表中。
    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2012-05-24
    • 1970-01-01
    相关资源
    最近更新 更多