在c#中使用tcp或存储过程批量插入documentdb

时间:2017-03-20 05:47:23

标签: c# asp.net-web-api2 azure-cosmosdb document-database

这是我的c#代码

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;
}

参数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; }
    }

解释了我需要的最终结果。

所以最初我打电话给外部API来获取酒店详细信息和他们的库存,所以这里是一个示例请求和我在调用外部API后得到的响应

请求为json:

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

我回复的回应

{
"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"
        }
    ]
}
}

我回来的回应的模型类

        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; }

    }

所以我有一个1500家酒店的列表,我将调用其余的API来获取每个酒店及其库存详情。反过来我希望每个响应都作为单个文档保存在documentdb中,所以总的来说我应该有我的收藏中有1500个文件。如果我做foreach并使用createdocumentasync方法将是一个正确的选择,或者我可以在列表中包含所有1500个文档详细信息后批量插入记录。需要你的建议和帮助!

提前致谢!

1 个答案:

答案 0 :(得分:0)

您的代码不是传统的ado.net,但在我看来,我强烈建议您使用bulkinsert,因为这是为大规模插入文件/数据/文档而设计的。您只需要在插入之前循环所有1500个文档。