• azure cosmosdb 测试


    https://www.cnblogs.com/AllenMaster/p/14049187.html复制了整个项目,不过发现了几个问题。

    • 源码中使用的是UserModel.Id,结果生成new item的时候老是报"/id" missing的错误
      试了以后发现,改成小写的id就可以了,再调查发现id不一定是partitionKey,但必须存在。所以就新加了id属性,使用identity作为partition Key。
    • UserModel
    class UserModel
    {
        public string id { get; set; }    // 必须有这么个属性
        public string identity { get; set; }    // partition key
        public string Name { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
        public string Remark { get; set; }
    }
    
    • appsettings.json
    {
      "CosmosDB": {
        "ConnectionString": "",  # copy connection string of cosmosdb account in azure 
        "DataBase": "db1",
        "Container": "container2"
      }
    }
    
    • CosmosDBClient
      • 新加记录调用CreateItemAsync()时,id和partitionKey要有值。
      • 在更新和删除时,会显式用到id和partitionKey,
    class CosmosDBClient
    {
        private CosmosClient cosmosClient;
        private Database database;
        private Container container;
    
        public async Task Init(IConfiguration configuration)
        {
            cosmosClient = new CosmosClient(configuration["CosmosDB:ConnectionString"]);
    
            #region Create CosmosDB
            string dbconn = configuration["CosmosDB:DataBase"];
    
            this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(dbconn);
            Console.WriteLine("Created Database:{0} Success
    ", dbconn);
            #endregion
    
            #region Create Container,使用identity作为partition key. 
            container = await this.database.CreateContainerIfNotExistsAsync(configuration["CosmosDB:Container"], "/identity");
            #endregion
        }
    
        public async Task InitItem()
        {
            //Create a UserModel object for the Andersen family
            var user1 = new UserModel
            {
                id = "1001",
                identity = "id-1",
                Name = "张无忌",
                Age = 12,
                Address = "北京市西城区鲍家街43号",
                Remark = "中央音乐学院"
            };
    
            var user2 = new UserModel
            {
                id = "1002",
                identity = "id-2",
                Name = "令狐冲",
                Age = 20,
                Address = "佛山市南海区灯湖东路6号",
                Remark = "广发商学院"
            };
    
            #region Query User1 of '张无忌'
            var user1s = await QueryItems(user1.Name);
            #endregion
    
    
            #region Add User1 Item
            if (user1s.Count <= 0)
            {
                ItemResponse<UserModel> user1Response = await this.container.CreateItemAsync<UserModel>(user1, new PartitionKey(user1.identity));
    
                Console.WriteLine("Created Item in database with id:{0} Operation consumed {1} RUs.
    ", user1Response.Resource.identity, user1Response.StatusCode);
            }
            #endregion
    
    
            #region Query User2 of '令狐冲'
            var user2s = await QueryItems(user2.Name);
            #endregion
    
            #region Add User2 Item
            if (user2s.Count <= 0)
            {
                ItemResponse<UserModel> user2Response = await this.container.CreateItemAsync<UserModel>(user2, new PartitionKey(user2.identity));
    
                Console.WriteLine("Created Item in database with id:{0} Operation consumed {1} RUs.
    ", user2Response.Resource.identity, user2Response.StatusCode);
            }
            #endregion
        }
    
        public async Task<List<UserModel>> QueryItems(string name)
        {
            var sqlQueryText = "SELECT * FROM c where 1=1";
    
            if (!string.IsNullOrEmpty(name))
            {
                sqlQueryText += " and c.Name='" + name + "'";
            }
    
            Console.WriteLine("Running query: {0}
    ", sqlQueryText);
    
            QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
    
            var users = new List<UserModel>();
            var queryUsers = this.container.GetItemQueryIterator<UserModel>(queryDefinition);
    
    
            while (queryUsers.HasMoreResults)
            {
                FeedResponse<UserModel> currentResultSet = await queryUsers.ReadNextAsync();
                foreach (UserModel user in currentResultSet)
                {
                    Console.WriteLine("	Read {0}
    ", user.Name);
                    users.Add(user);
                }
            }
            return users;
        }
    
        public async Task ModifyItem(string name)
        {
            List<UserModel> users = await QueryItems(name);
    
            UserModel modifyUser = users.FirstOrDefault();
            modifyUser.Address = "上海市静安区石板街73弄";
            
            var modifyResponse = await this.container.ReplaceItemAsync<UserModel>(modifyUser, modifyUser.id, new PartitionKey(modifyUser.identity));
            Console.WriteLine("name equal to '" + name + "',his family address modify {0}
    ", modifyResponse.StatusCode == HttpStatusCode.OK ? "success" : "fail");
        }
    
        public async Task DeleteItem(string name)
        {
            List<UserModel> users = await QueryItems(name);
            UserModel found = users.First();
    
            var deleteResponse = await this.container.DeleteItemAsync<UserModel>(found.id, new PartitionKey(found.identity));
    
            Console.WriteLine("delete'" + name + " item'{0}
    ", deleteResponse.StatusCode == HttpStatusCode.NoContent ? "success" : "fail");
        }
    }
    
    • 测试
    public static async Task Main(string[] args)
    {
        IConfiguration configuration = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", false, true)
            .Build();
    
        CosmosDBClient client = new CosmosDBClient();
    
        try
        {
            await client.Init(configuration);
            await client.InitItem();
    
            await client.QueryItems(string.Empty);
            await client.ModifyItem("张无忌");
            await client.DeleteItem("令狐冲");
            await client.QueryItems(string.Empty);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
        }
    }
    
    --------------------------- 知道的更多,不知道的也更多 ---------------------------
  • 相关阅读:
    【Python学习】读取Excel文件,并写入Excel
    异步编程
    LINQ入门
    [Leetcode Weekly Contest]207
    [Leetcode Weekly Contest]203
    VsCode插件,自动生成注释koroFileHeader
    vue样式穿透 ::v-deep的具体使用
    springcloud,springboot,springcloud-alibaba 之间版本关系
    sharding-sphere 单库分表实例
    CDN动态加速技术
  • 原文地址:https://www.cnblogs.com/mryux/p/15357993.html
Copyright © 2020-2023  润新知