2017-03-20 10 views
0

여기 내 C# 코드대량 삽입 C#에서 TCP 또는 저장 프로 시저를 사용 documentdb

public static async Task<Database> GetDatabase(string databaseName) 
{ 
     if (client.CreateDatabaseQuery().Where(db => db.Id == 
       databaseName).AsEnumerable().Any()) 
     { 
      return client.CreateDatabaseQuery().Where(db => db.Id == 
       databaseName).AsEnumerable().FirstOrDefault(); 
     } 
     return await client.CreateDatabaseAsync(new Database 
     { 
      Id = databaseName 
     }); 
} 

//check if collection already exists 
public static async Task<DocumentCollection> GetCollection(Database database, string collName) 
{ 
     if (client.CreateDocumentCollectionQuery 
       (database.SelfLink).Where(coll => coll.Id == 
       collName).ToArray().Any()) 
     { 
      return client.CreateDocumentCollectionQuery(database.SelfLink). 
        Where(coll => coll.Id == 
      collName).ToArray().FirstOrDefault(); 
     } 
     return await client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection 
     { Id = collName }); 
} 

[Route("getHotelDetails")] 
[HttpPost] 
public HttpResponseMessage getHotelDetails(RootObj rootObj) 
{ 
     var result = ""; 

     Database database = GetDatabase("sampledb").Result; 

     DocumentCollection collection = GetCollection(database, "samplecollection").Result;   

     string convertListToJson = JsonConvert.SerializeObject(rootObj); 

     try 
     { 
      var url = "http://www.example.com"; 
      HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; 
      request.Method = "POST"; 
      request.ContentType = "application/json; encoding='utf-8'"; 
      request.Credentials = GetCredential(); 
      request.PreAuthenticate = true; 
      using (var streamWriter = new StreamWriter(request.GetRequestStream())) 
      { 
       streamWriter.Write(convertListToJson); 
       streamWriter.Flush(); 
      } 
      var httpResponse = (HttpWebResponse)request.GetResponse(); 

      using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
      { 
       result = streamReader.ReadToEnd(); 
      } 
     } 
     catch (WebException ex) 
     { 
      // Log exception and throw as for GET example above 

      HttpResponseMessage resp = Request.CreateResponse(HttpStatusCode.ExpectationFailed, ex.Message.ToString()); 
      return resp; 
     } 

     RootObject obj = JsonConvert.DeserializeObject<RootObject>(result); 
     HttpResponseMessage res = Request.CreateResponse(HttpStatusCode.OK, obj); 
     return res; 
} 

private CredentialCache GetCredential() 
{ 
     string url = @"http://www.example.com"; 
     ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; 
     CredentialCache credentialCache = new CredentialCache(); 
     credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential("xxx", "yyy")); 
     return credentialCache; 
} 

그리고 매개 변수 I는 설명이 필요 rootObj

public class HotelCriteria 
{ 
    public string HotelCode { get; set; } 
} 

public class RoomRatePlans 
{ 
    public HotelCriteria HotelCriteria { get; set; } 
} 

    public class RootObj 
    { 
     public string Version { get; set; } 
     public string EchoToken { get; set; } 
     public RoomRatePlans RoomRatePlans { get; set; } 
    } 

최종 결과에 대한 모델 클래스입니다.

{ 
    "Version": "1.2", 
    "EchoToken": "879791878", 
    "RoomRatePlans": { 
    "HotelCriteria": { 
    "HotelCode": "101920" 
    } 
    } 
} 
:

그래서 처음에 내가 그래서 여기에 호텔의 자세한 사항과 재고를 얻기 위해 외부 API를 호출하고하는 것은 내가 외부 API를 JSON으로

요청을 호출 한 후 다시 얻을 샘플 요청 및 응답의

그리고 내가 돌아올 응답에 대한

{ 
"HotelCriteria": { 
    "HotelCode": "NONIDS", 
    "HotelName": "TestThe Zuri Whitefield Bengaluru" 
}, 
"RoomTypes": { 
    "RoomTypeList": [ 
     { 
      "InvTypeCode": "ZCR", 
      "Name": "Zuri Club Room", 
      "BaseOccupancy": 2, 
      "MaxOccupancy": 3, 
      "Quantity": 66, 
      "IsRoomActive": 1, 
      "RoomDescription": "" 
     }, 
     { 
      "InvTypeCode": "ZRR", 
      "Name": "Zuri Room", 
      "BaseOccupancy": 2, 
      "MaxOccupancy": 3, 
      "Quantity": 90, 
      "IsRoomActive": 1, 
      "RoomDescription": "" 
     }, 
     { 
      "InvTypeCode": "ZSR", 
      "Name": "Zuri Suite Room", 
      "BaseOccupancy": 2, 
      "MaxOccupancy": 3, 
      "Quantity": 4, 
      "IsRoomActive": 1, 
      "RoomDescription": "" 
     } 
    ] 
}, 
"RatePlans": { 
    "RatePlanList": [ 
     { 
      "RatePlanCode": "B2C00001", 
      "RatePlanCategory": "B2C", 
      "RatePlanStatusType": 1, 
      "RatePlanName": "Channel Rates", 
      "Description": "Channel Rates", 
      "InvTypeCode": "ZCR", 
      "MealPlanCode": "CP", 
      "MealPlanDesc": "Continental Plan", 
      "Start": "2016-06-27", 
      "End": "2017-03-31", 
      "CurrencyCode": "INR" 
     }, 
     { 
      "RatePlanCode": "B2C00001", 
      "RatePlanCategory": "B2C", 
      "RatePlanStatusType": 1, 
      "RatePlanName": "Channel Rates", 
      "Description": "Channel Rates", 
      "InvTypeCode": "ZRR", 
      "MealPlanCode": "CP", 
      "MealPlanDesc": "Continental Plan", 
      "Start": "2016-06-27", 
      "End": "2017-03-31", 
      "CurrencyCode": "INR" 
     }, 
     { 
      "RatePlanCode": "B2C00001", 
      "RatePlanCategory": "B2C", 
      "RatePlanStatusType": 1, 
      "RatePlanName": "Channel Rates", 
      "Description": "Channel Rates", 
      "InvTypeCode": "ZSR", 
      "MealPlanCode": "CP", 
      "MealPlanDesc": "Continental Plan", 
      "Start": "2016-06-27", 
      "End": "2017-03-31", 
      "CurrencyCode": "INR" 
     } 
    ] 
}, 
"Inclusions": { 
    "InclusionList": [ 
     { 
      "MealPlanCode": "CP", 
      "MealPlanDesc": "Continental Plan" 
     } 
    ] 
} 
} 

모델 클래스는 내가 다시

,536,913를 얻을 응답
 public class HotelCriteria 
    { 
     public string HotelCode { get; set; } 
     public string HotelName { get; set; } 
    } 

    public class RoomTypeList 
    { 
     public string InvTypeCode { get; set; } 
     public string Name { get; set; } 
     public int BaseOccupancy { get; set; } 
     public int MaxOccupancy { get; set; } 
     public int Quantity { get; set; } 
     public int IsRoomActive { get; set; } 
     public string RoomDescription { get; set; } 
    } 

    public class RoomTypes 
    { 
     public List<RoomTypeList> RoomTypeList { get; set; } 
    } 

    public class RatePlanList 
    { 
     public string RatePlanCode { get; set; } 
     public string RatePlanCategory { get; set; } 
     public int RatePlanStatusType { get; set; } 
     public string RatePlanName { get; set; } 
     public string Description { get; set; } 
     public string InvTypeCode { get; set; } 
     public string MealPlanCode { get; set; } 
     public string MealPlanDesc { get; set; } 
     public string Start { get; set; } 
     public string End { get; set; } 
     public string CurrencyCode { get; set; } 
    } 

    public class RatePlans 
    { 
     public List<RatePlanList> RatePlanList { get; set; } 
    } 

    public class InclusionList 
    { 
     public string MealPlanCode { get; set; } 
     public string MealPlanDesc { get; set; } 
    } 

    public class Inclusions 
    { 
     public List<InclusionList> InclusionList { get; set; } 
    } 

    public class RootObject 
    { 
     public HotelCriteria HotelCriteria { get; set; } 
     public RoomTypes RoomTypes { get; set; } 
     public RatePlans RatePlans { get; set; } 
     public Inclusions Inclusions { get; set; } 

    } 

그래서 나머지 API를 각각의 호텔 및 인벤토리 세부 정보를 얻기 위해 호출 할 1500 개의 호텔 목록이 있습니다. 차례로 각 응답은 단일 문서로서 documentdb에 저장되기를 원합니다 나는 내 collection에 1500 개의 문서를 가져야한다. foreach를 사용하고 createdocumentasync 메서드를 사용하면 올바른 선택이 될 것이고리스트에 내 1500 개의 문서 세부 사항을 모두 삽입 한 후에 대량으로 레코드를 삽입 할 수있다. 당신의 제안과 도움을 필요로한다!

미리 감사드립니다.

답변

0

귀하의 코드는 전통적인 ado.net이 아니지만 제 의견으로는 파일/데이터/문서의 대량 삽입을 위해 설계되었으므로 bulkinsert를 사용하는 것이 좋습니다. 한 번에 삽입하기 전에 모든 1500 개의 문서를 반복하면됩니다.

+0

for 루프를 사용하여 목록에 추가 한 다음 대량 삽입을 수행 하시겠습니까? BTW 이것은 ado.net하지 않습니다. 나는 C# 웹 API 2와 azure documentdb를 사용하고 있습니다. – Melvin

+0

예, 정확하게! 나는 웹 API 2를 사용하지 않았지만 asmx 만 사용할 수 있지만 전통적인 ado.net은 여전히 ​​mvc/web API에서 사용할 수 있지만 사용하기에 편한 곳에서 붙여야합니다. 동일한 논리/접근법 –