假设您有这样的表结构:
Patient -> PatientTag ->标签
患者和标签之间是典型的N:M关系,PatientTag是两个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();
}感谢你对这个主题的见解。
发布于 2009-12-01 21:26:19
简单地使用带有级联delete的外键,然后删除标记本身,并让数据库负责删除所有引用,会怎么样呢?如果您希望确保它未在使用中,可以先检查是否没有任何患者与其关联,但如果有其他进程访问同一数据库,则可能需要将其包装在一个事务中。
发布于 2009-12-01 22:32:09
我同意tvanfosson在数据库上这样做。另一种方法(imho可能更安全)是创建一个选通过程并从代码中调用它。确保所有事务都封装在一个事务中,以便在出现问题时处理回滚
https://stackoverflow.com/questions/1826061
复制相似问题