代码之家  ›  专栏  ›  技术社区  ›  Oleks

LINQ to SQL:使用软删除筛选嵌套对象

  •  1
  • Oleks  · 技术社区  · 16 年前

    IsDeleted 字段)。我正在积极使用 LoadWith AssociateWith

    联系

    DataLoadOptions loadOptions = new DataLoadOptions();
    loadOption.LoadWith<User>(u = > u.Roles);
    loadOption.AssociateWith<User>(u = > u.Roles.Where(r = > !r.IsDeleted));
    

    在上面的例子中,我只是说: 我要检索具有相关(未删除)角色的用户 .

    但当我有一对一的关系时,例如。 Document File (只有一个文件与文档相关)我无法筛选软删除对象:

    DataLoadOptions loadOptions = new DataLoadOptions();
    loadOption.LoadWith<Document>(d = > d.File);
    // the next certainly won't work
    loadOption.AssociateWith<File>(f = > !f.IsDeleted);
    

    2 回复  |  直到 16 年前
        1
  •  1
  •   Oleks    16 年前

    到目前为止,我只找到了一个合适的解决方案(除了完全不使用软删除之外):在实体更新时删除软删除关系。

    // this may be a part of update method
    var file = document.File;
    if (file.IsDeleted)
    {
        // attach soft deleted file
        context.Files.Attach(file, true); 
    
        // remove a file reference
        document.File = null;
    }
    
    // attach document entity and submit changes
    context.Documents.Attach(document, true);
    context.SubmitChanges();
    

    因此,这可以替代复杂数据检索中的一对一关系过滤。

        2
  •  0
  •   luke    16 年前

    或许可以试试:

    loadOptions.AssociateWith<File>(f => f.IsDeleted ? null : f);
    

    这将为您提供null,而不是IsDeleted为true的文件。

    推荐文章