无法使用LINQ检索其他插入的插入的对象ID

时间:2018-10-26 06:43:30

标签: c# linq linq-to-sql insert-id

我对LINQ to SQL有问题。我在数据库中插入了一个新的 DetailsComposantsMan (有效),并且我想插入一个新的 DetailsRep 指向我的 DetailsComposantsMan 插入的ID。

这些功能正常工作

  • InsertOnSubmit函数有效
  • SumbitChanges函数起作用

这是 DetailsComposantsMan

的插入代码
if (detailsComposantMan.Id == 0)
{
    DetailsComposantsMan inserted = new DetailsComposantsMan();
    inserted.Article_Id = detailsComposantMan.Article_Id;
    inserted.BlocFonctionnel_Id = detailsComposantMan.BlocFonctionnel_Id;
    inserted.CategorieComposant_Id = detailsComposantMan.CategorieComposant_Id;
    inserted.DetailComposant = detailsComposantMan.DetailComposant;
    inserted.Fabricant = detailsComposantMan.Fabricant;
    inserted.IndicationSAV_Id = detailsComposantMan.IndicationSAV_Id;
    inserted.IsMAJ = detailsComposantMan.IsMAJ;
    inserted.IsActive = true;
    inserted.NumPieceStuder = detailsComposantMan.NumPieceStuder;
    inserted.PositionSchema = detailsComposantMan.PositionSchema;
    db.DetailsComposantsMans.InsertOnSubmit(inserted);
}
// Autrement on tente de trouver le details a update
else
{
    #region Update DetailsComposantsMan
    DetailsComposantsMan updated = lst.Single(x => x.Id == detailsComposantMan.Id);
    updated.Id = detailsComposantMan.Id;
    updated.Article_Id = detailsComposantMan.Article_Id;
    updated.BlocFonctionnel_Id = detailsComposantMan.BlocFonctionnel_Id;
    updated.CategorieComposant_Id = detailsComposantMan.CategorieComposant_Id;
    updated.DetailComposant = detailsComposantMan.DetailComposant;
    updated.Fabricant = detailsComposantMan.Fabricant;
    updated.IndicationSAV_Id = detailsComposantMan.IndicationSAV_Id;
    updated.IsMAJ = detailsComposantMan.IsMAJ;
    updated.IsActive = detailsComposantMan.IsActive;
    updated.NumPieceStuder = detailsComposantMan.NumPieceStuder;
    updated.PositionSchema = detailsComposantMan.PositionSchema;
    #endregion
}
try
{
    // Submit tout les changements
    db.SubmitChanges();
}
catch (Exception E)
{
    // Si erreur on la balance au try catch supérieur
    throw E;
}

插入后,我创建一个新对象 DetailsRep ,并将DetailsComposantsMan_Id字段的值设置为0。

dbConn.updateOrinsertDetailsComposantMan(newDetailsComposantsMan);

// Si c'est une mise à jour, créer une nouvelle DetailsRep
DetailsRep newDetailsRep = new DetailsRep();
newDetailsRep.Quantity = 1;
newDetailsRep.Rep_Id = sav.Id;                             
// PROBLEM HERE (ID = 0) !!!                        
newDetailsRep.DetailComposantMan_Id = newDetailsComposantsMan.Id;

这是一个外键,因此,如果该字段的值为0,则它​​将无效。谁能帮我吗?

0 个答案:

没有答案