代码之家  ›  专栏  ›  技术社区  ›  Martin Marconcini

删除plinqo中m:m的正确方法?

  •  0
  • Martin Marconcini  · 技术社区  · 15 年前

    假设您有这个表结构:

    患者->患者标签->标签

    患者和标签之间典型的N:M关系,患者标签是两个FK的中间实体。(PatientID和Tagid)。

    我想删除一个特定的标签,我有它的ID。我想知道有没有更好的方法,因为这些是我第一次使用plinqo编写的方法,我不想从头开始创建坏的实践。

                using ( MyDataContext dc = DataContextFactory.GetDataContext() )
                {
    
                    var options = new DataLoadOptions();
                    options.LoadWith<Paciente>(p => p.PacienteTagList);
                    options.LoadWith<PacienteTag>(pt => pt.Tag);
                    dc.LoadOptions = options;
    
                    // Get the Tag we're going to remove from the DB.
                    var tag = dc.Manager.Tag.GetByKey( idTag);
    
                    // Remove each patient from the association. 
                    foreach ( Paciente pac in tag.PacienteList1 )
                    {
                        // we need to retrieve it, won’t let us use the ‘pac’ object.
                        var pax = dc.Manager.Paciente.GetByKey( pac.IdPaciente );
                        pax.TagList.Remove(tag);
                    }
    
                    // now remove the tag
                    dc.Manager.Tag.Delete(tag.TagId);
    
                    // And commit the changes
                    dc.SubmitChanges();
                }
    

    谢谢你对这个问题有任何见解。

    2 回复  |  直到 15 年前
        1
  •  1
  •   tvanfosson    15 年前

    简单地将一个外键与级联删除一起使用,然后删除标记本身,让数据库负责删除所有引用。如果您想确保它没有被使用,您可以先检查是否有任何患者与它关联,但是如果有其他进程访问同一数据库,您可能需要将它包装在事务中。

        2
  •  2
  •   Rippo    15 年前

    我同意Tvanfosson在数据库中做这件事。另一种方法(可能是更安全的imho)是创建一个strured过程并从代码中调用它。确保所有的事务都包含在一个事务中,该事务可以在出现问题时处理回滚。