使用c# linq对Cassandra进行增删改查

Cassandra是一个Wide-column store,类似于HBase,nosql的一种,它有一个“静态列(static column)”,可以只更新一列中的一个colum,特别酷炫。
其他的功能我还在研究中。

参考:https://github.com/datastax/csharp-driver?spm=a2c4g.11186623.2.16.1ccd4c3e1nr5ti

1.安装驱动

在Nuget管理搜索"CassandraCSharpDriver"或者命令安装:


image.png
Install-Package CassandraCSharpDriver

2.使用linq进行增删改查

就像我们平时使用EF一样,十分简单:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Cassandra;
using Cassandra.Mapping;
using Cassandra.Data.Linq;

namespace ConsoleApp1
{
    public class User
    {
        public Guid UserId { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public override string ToString()
        {
            return $"UserId: {UserId}, Name: {Name}, Age: {Age}";
        }
    }


    class Program
    {
        public ICluster Cluster { get; set; }
        public ISession Session { get; set; }
        public static Guid User0Guid { get; set; }

        private static void Main(string[] args)
        {
            new Program().MainAsync(args).GetAwaiter().GetResult();
        }

        private async Task MainAsync(string[] args)
        {
            User0Guid = Guid.NewGuid();
            // build cluster connection
            Cluster =
                Cassandra.Cluster.Builder()
                    .AddContactPoint("127.0.0.1")
                    .Build();

            //Set the Mapping Configuration
            MappingConfiguration.Global.Define(
               new Map()
                  .TableName("users")
                  .PartitionKey(u => u.UserId)
                  .Column(u => u.UserId, cm => cm.WithName("id")));

            // create session
            Session = await Cluster.ConnectAsync().ConfigureAwait(false);

            // prepare schema
            await Session.ExecuteAsync(new SimpleStatement("CREATE KEYSPACE IF NOT EXISTS examples WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '1' }")).ConfigureAwait(false);
            await Session.ExecuteAsync(new SimpleStatement("USE examples")).ConfigureAwait(false);
            await Session.ExecuteAsync(new SimpleStatement("CREATE TABLE IF NOT EXISTS users(id uuid, name text, age int, PRIMARY KEY(id))")).ConfigureAwait(false);

            //以上,创建一个session


            try
            {
                //Create an instance of a Mapper from the session
                var users = new Table(Session);
                await InsertOperations(users);
                await QueryOperations(users);
                await UpdateOperations(users);
                await DeleteOperations(users);
            }
            finally
            {
                await Cluster.ShutdownAsync().ConfigureAwait(false);
            }
        }

        /// 
        /// Demonstrates how to delete via Linq
        /// 删除
        /// 
        /// 
        private static async Task DeleteOperations(Table users)
        {
            // Delete
            await users.Where(u => u.UserId == User0Guid)
                  .Delete()
                  .ExecuteAsync();

            // Delete If 
            await users.Where(u => u.UserId == User0Guid)
                  .DeleteIf(u => u.Name == "User 0")
                  .ExecuteAsync();
        }

        /// 
        /// Demonstrates the ability to update via Linq
        /// 更新
        /// 
        /// 
        private static async Task UpdateOperations(Table users)
        {
            await users.Where(u => u.UserId == User0Guid)
                .Select(u => new User { Name = "Update Linq" })
                .Update()
                .ExecuteAsync();
            var user = await users.Where(u => u.UserId == User0Guid).ExecuteAsync();
        }

        /// 
        /// Demonstrates the different query methods allowed via Linq. 
        /// 查找
        /// 
        /// 
        private static async Task QueryOperations(Table users)
        {
            IEnumerable usrs = await users.Select(a => a).ExecuteAsync();
            Console.WriteLine($"Retrieved {usrs.Count()} users");
            usrs = await users.Where(u => u.UserId == User0Guid).ExecuteAsync();
            Console.WriteLine($"Retrieved {usrs.Count()} users");
            var usr = await users.Where(u => u.UserId == User0Guid).First().ExecuteAsync();
            Console.WriteLine($"Retrieved {usr.ToString()}");
            usr = await users.Where(u => u.UserId == User0Guid).FirstOrDefault().ExecuteAsync();
            Console.WriteLine($"Retrieved {usr.ToString()}");
        }

        /// 
        /// Demonstrates how to perform singular insert operations using Linq
        /// 添加
        /// 
        /// The User table
        /// 
        private static async Task InsertOperations(Table users)
        {
            //Insert a single record using a POCO
            await users.Insert(new User() { UserId = User0Guid, Name = "User 0", Age = 0 }).ExecuteAsync();
        }
    }
}

你可能感兴趣的:(使用c# linq对Cassandra进行增删改查)