ServiceStack.OrmLite 基本操作

原文:https://www.cnblogs.com/wang2650/category/780821.html

原文:https://www.cnblogs.com/xxfcz/p/7045808.html

注意一下环境哦,这里我使用的版本是 4.0.62,不同版本语法上肯定是有差异的,

还有就是为什么装的是个老版本,本地的VS装不了最新的版本,新版本好像要用到Core 2.0。以后再试试最近的版本了,空了来。

全部代码:

using ServiceStack;
using ServiceStack.DataAnnotations;
using ServiceStack.OrmLite;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2.test1
{
    public class Class12
    {
        //ServiceStack.OrmLite
        //原文:https://www.cnblogs.com/xxfcz/p/7045808.html
        //原文:https://www.cnblogs.com/wang2650/category/780821.html

        public void test1()
        {
            //查询数据
            string connString = "data source=.\\sqlexpress;initial catalog=MyDbContext;user id=sa;password=sa;";
            var dbFactory = new OrmLiteConnectionFactory(connString, SqlServerDialect.Provider);
            using (var db = dbFactory.Open())
            {
                var roles = db.Select<Book>();
                "Roles: {0}".Print(roles.Dump());//输出到控制台
            }
        }

        public void test2()
        {
            //创建表,如果表已存在,那么删除后再创建
            OrmLiteConfig.DialectProvider = SqlServerDialect.Provider;
            string connString = "data source=.\\sqlexpress;initial catalog=MyDbContext;user id=sa;password=sa;";
            using (var db = connString.OpenDbConnection())
            {
                db.DropAndCreateTable<Book2>();
            }
        }

        public void test3()
        {
            //创建表,并插入一条数据。表如果已存在,则不插入数据
            string connectionString = "data source=.\\sqlexpress;initial catalog=MyDbContext;user id=sa;password=sa;";
            var dbFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);
            using (var db = dbFactory.Open())
            {
                if (db.CreateTableIfNotExists<Book2>())
                {
                    db.Insert(new Book2 { Id = 1, Name = "Seed Data" });
                }
            }
        }

        public void test4()
        {
            //插入
            string connectionString = "data source=.\\sqlexpress;initial catalog=MyDbContext;user id=sa;password=sa;";
            var dbFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);
            using (var db = dbFactory.Open())
            {
                //db.CreateTableIfNotExists<Book2>();
                //db.Insert(new Book2 { Id = 1, Name = "Seed Data1" });
                //db.Insert(new Book2 { Id = 2, Name = "Seed Data2" });
                //db.Insert(new Book2 { Id = 3, Name = "Seed Data3" });
                //db.Insert(new Book2 { Id = 4, Name = "Seed Data4" });
                //db.Insert(new Book2 { Id = 5, Name = "Seed Data5" });

                ////异步 新增
                //Task<long> task = db.InsertAsync(new Book2 { Id = 6, Name = "Seed Data6" });
                //Console.WriteLine("The Sum is:" + task.Result);

                ////只新增 指定字段
                //db.InsertOnly<Book2>(new Book2 { Id = 6, Name = "Seed Data6" }, c => c.Id);

                ////新增数据 返回自增长ID。 这里需要修改一下环境,数据库表设置主键、设置自增长,Model的Id增加特性AutoIncrement、PrimaryKey
                //long id = db.Insert(new Book2 { Name = "Seed Data5" }, selectIdentity: true);
                //Console.WriteLine(id);

                ////插入数据的时候,自动插入创建时间等 通用字段
                ////全局的 插入时 过滤
                //OrmLiteConfig.InsertFilter = (dbCmd, row) => {
                //    var auditRow = row as BaseEntity;
                //    if (auditRow != null)
                //        auditRow.CreatedDate = auditRow.ModifiedDate = DateTime.UtcNow;
                //};
                ////db.CreateTableIfNotExists<Book3>();
                //db.Insert(new Book3 { Id = 3, Name = "Seed Data3" });
                //db.Insert(new Book3 { Id = 4, Name = "Seed Data4" });
                //db.Insert(new Book3 { Id = 5, Name = "Seed Data5" });

                ////直接执行sql语句
                //db.ExecuteSql("INSERT INTO Book2 (Id, Name) VALUES (@Id, @Name)", new Book2 { Id = 5, Name = "Seed Data5" });

                //批量添加
                int i = 0;
                var rows = "A,B,B,C,C,C,D,D,E".Split(‘,‘).Map(x => new Book2 { Name = x, Id = (i++) });
                db.InsertAll(rows);
            }
        }

        public void test5()
        {
            //删除
            string connectionString = "data source=.\\sqlexpress;initial catalog=MyDbContext;user id=sa;password=sa;";
            var dbFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);
            using (var db = dbFactory.Open())
            {
                //db.DeleteById<Book2>(0);
                //db.Delete<Book2>(new Book2 { Id = 1, Name = "B" });
                //db.Delete<Book2>(p => p.Name == "D");

                ////这里没有测试成功,原因未知
                //var updatedRow = db.SingleById<Book4>(1); // fresh version
                //db.DeleteById<Book4>(id: updatedRow.Id, rowVersion: updatedRow.RowVersion);
            }
        }

        public void test6()
        {
            string connectionString = "data source=.\\sqlexpress;initial catalog=MyDbContext;user id=sa;password=sa;";
            var dbFactory = new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider);
            using (var db = dbFactory.Open())
            {
                //db.Update(new Book2 { Id = 2, Name="BB" });
                // sql:UPDATE "Person" SET "FirstName" = ‘Jimi‘,"LastName" = ‘Hendrix‘,"Age" = 27 WHERE "Id" = 1

                //db.Update(new Book2 { Id=1, Name = "CCCC" }, p => p.Name == "BBCCB");
                //Console.WriteLine(db.GetLastSql());

                ////部分更新
                //db.UpdateNonDefaults(new Book2 { Name = "CC" }, p => p.Name == "CCCC");

                ////部分更新
                //db.UpdateOnly(new Book2 { Name = "DD" },
                //onlyFields: p => new { p.Name },
                //where: p => p.Id == 1);

                //先获取 再更新
                var updatedRow = db.SingleById<Book2>(1);
                updatedRow.Name = "AA";
                db.Update(updatedRow);

                //打印SQL语句
                Console.WriteLine(db.GetLastSql());
            }
        }

        public void test7()
        {

        }

        public class Book4
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public ulong RowVersion { get; set; }
        }

        public class BaseEntity
        {
            public int Id { get; set; }
            public DateTime CreatedDate { get; set; }
            public DateTime ModifiedDate { get; set; }
            public string ModifiedBy { get; set; }
        }

        public class Book3 : BaseEntity
        {
            public string Name { get; set; }
        }

        [Serializable]
        [Alias("Book2")]
        public class Book2
        {
            //[AutoIncrement]
            //[PrimaryKey]
            public int Id { get; set; }
            public string Name { get; set; }
        }

        [Serializable]
        [Alias("Book")]
        public class Book
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    }
}

原文地址:https://www.cnblogs.com/guxingy/p/11195045.html

时间: 2024-10-11 09:01:10

ServiceStack.OrmLite 基本操作的相关文章

ServiceStack.OrmLite简单扩展

ServiceStack.OrmLite框架将所有的方法都扩展到了一个IDbConnection对象上,使用起来不是 很方便,在此对该框架做一个简单的封装. OrmLiteExecFilterExt类 using System; using System.Collections.Generic; using System.Data; using System.Text; using System.Threading.Tasks; namespace ServiceStack.OrmLite.Ex

ServiceStack.OrmLite中的一些&quot;陷阱&quot;(1)

使用过ServiceStack.Ormlite的人都应该知道,其作为一个轻量级的ORM,使用的便捷度非常高,用起来就一个字:爽!而支撑其便捷度的,是库内大量地使用了扩展方法及静态变量. 首先先从源头入手分析(以下以Sqlite为例): OrmLiteConfig.DialectProvider = SqliteOrmLiteDialectProvider.Instance; using (IDbConnection db = "~/db.sqlite".MapAbsolutePath(

ServiceStack.OrmLite中的一些&quot;陷阱&quot;(2)

注:此系列不是说ServiceStack.OrmLite的多个陷阱,这仅仅个人认为是某一个陷阱(毕竟我踩坑了)而引发的思考. 前文说到了项目需要使用两种不同的数据库语言,虽说前文问题已基本解决了,但是我发现OrmLite在设计上有需要改进的地方.正如前面提到的OrmLite为了开发的便捷性,ORM所需要生成SQL语句DialectProvider设置为静态属性(尽管使用了线程安全),但是这样的话DialectProvider便与线程上下文产生耦合. 而一个更优的方法,则是使用代理.第一次对代理产

ServiceStack.OrmLite 入门(一)

软件环境: Win7 x64 SP1 SQL Server 2008r2 Visual Studio 2017 Professional 目标:取出示例数据库 ReportServer 的表 Roles 中的所有记录并显示. 步骤: 一.添加软件包 使用NuGet添加以下软件包: ServiceStack ServiceStack.OrmLite 二.定义表类 根据表Roles来定义对应的C#类: [Serializable] [Alias("Roles")] public class

ServiceStack.OrmLite破解

在 ServiceStack.OrmLite下的 OrmLiteConfigExtensions 第199行把这句注释掉就可以了 //LicenseUtils.AssertValidUsage(LicenseFeature.OrmLite, QuotaType.Tables, typeModelDefinitionMap.Count);

ServiceStack.OrmLite 调用存储过程

最近在做关于ServiceStack.OrmLite调用存储过程时,有问题.发现ServiceStack.OrmLite不能调用存储过程,或者说不能实现我想要的需求.在做分页查询时,我需要传入参数传出参数. ServiceStack.OrmLite 调用存储过程代码: 存储过程:usp_GetCarComponentsList 传入参数:@page,@limit 传出参数:@pageCount ,@totalCount 问题描述:参数传入在数据库中不能接收,不知道是写法问题,还是其他原因.即便传

ServiceStack.OrmLite

A Fast, Simple, Typed ORM for .NET OrmLite's goal is to provide a convenient, DRY, config-free, RDBMS-agnostic typed wrapper that retains a high affinity with SQL, exposing intuitive APIs that generate predictable SQL and maps cleanly to (DTO-friendl

ServiceStack OrmLite 连接Sqlserver数据库

技术交流群:665060698 ServiceStack是一个.net的服务类库,包含的数据处理非常丰富,执行效率也非常高, 但ServiceStack也不止是用来写服务,也可以引用其中的dll进行数据库的连接操作,ServiceStack OrmLite支持的数据类型也很多,包括Sqlserver.Mysql.Postgresql.Sqlite等,下边分享一个 简单 ServiceStack OrmLite的连接sqlserver数据库,并获取数据.  var _sqlserverFla = 

ServiceStack.OrmLite中的一些&quot;陷阱&quot;(3)

前文说到如果使用多数据库(不同SQL方言)时要如何开发?其实前文(第二篇)也有“透露”到.就是直接使用库提供的OrmLiteConnection 及OrmLiteConnectionFactory(IDbConnectionFactory) .我们先来看下代理类是怎么实现的: public class OrmLiteConnection : IDbConnection, IHasDbConnection, IHasDbTransaction { public readonly OrmLiteCo