簡體   English   中英

在多種方法中使用相同的dbcontext

[英]Use the same dbcontext in multiple methods

我有一個問題,我會在多種方法中使用相同的dbContext,例如:

public class Communication
{
   public Response AddCommunication(Commnucation myComm)
   {
      using(MYDB dbContenxt = new MYDB())
       {
           DBCOMMUNICATION dbComm = new DBCOMMUNICATION
           {
               ID = myComm.Id,
               NAME = myComm.Name,
               SUBJECT = myComm.Subject,
               MESSAGE = myComm.Message
           };

           if(myComm.Images != null && myComm.Images.Count > 0)
           {
               foreach(var image in Images)
               {
                   IMAGES dbImages = new IMAGES
                   {
                       ID_COMMUNICATION = myComm.Id,
                       NAME = image.Name,
                       VALUE = image.Value
                   };
                   dbContext.IMAGES.add(dbImages);
               }
           }

           if(myComm.Attachments != null && myComm.Attachments.Count > 0)
           {
               foreach(var image in Images)
               {
                   same work .......
                }
           }
        dbContext.SaveChanges();    
       }
      .......
      .......
    }
}

我會提取使用foreach循環的方法,例如:

 if(myComm.Images != null && myComm.Images.Count > 0)
       {
            AddImages(myComm);
       }

在AddImages方法中,我將使用相同的dbContext進行添加,但僅在AddCommunication中使用SaveChanges。 哪個是最佳做法? 對dbContext使用單例模式? 請幫我。 謝謝,抱歉我的英語不好。

只需將dbContext傳遞給新方法

if(myComm.Images != null && myComm.Images.Count > 0)
{
   AddImages(dbContext, myComm);
}

...

private void AddImages(MYDB dbContext,Commnucation myComm)
{
   ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM