Fork me on GitHub

ASP.NET Core 1.0 使用 Dapper 操作 MySql(包含事务)

操作 MySql 数据库使用MySql.Data程序包(MySql 开发,其他第三方可能会有些问题)。

project.json 代码:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "emitEntryPoint": true
  },

  "dependencies": {
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.1"
    },
    "Dapper": "1.50.2",
    "MySql.Data": "7.0.6-IR31"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": "dnxcore50"
    }
  }
}

测试数据库脚本:

CREATE TABLE `products` (
  `ProductID` int(11) NOT NULL AUTO_INCREMENT,
  `Name` varchar(255) DEFAULT NULL,
  `Quantity` int(11) DEFAULT NULL,
  `Price` int(11) DEFAULT NULL,
  PRIMARY KEY (`ProductID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=gbk;

Product 代码:

public class Product
{
    [Key]
    public int ProductId { get; set; }
    public string Name { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
}

ProductRepository 代码(数据访问操作):

public class ProductRepository
{
    private string connectionString;
    public ProductRepository()
    {
        connectionString = @"server=localhost;database=dapperdemo;uid=root;pwd=123456;";
    }

    public IDbConnection Connection
    {
        get
        {
            return new MySqlConnection(connectionString);
        }
    }

    public void Add(Product prod)
    {
        using (IDbConnection dbConnection = Connection)
        {
            string sQuery = "INSERT INTO Products (Name, Quantity, Price)"
                            + " VALUES(@Name, @Quantity, @Price)";
            dbConnection.Open();
            dbConnection.Execute(sQuery, prod);
        }
    }

    public IEnumerable<Product> GetAll()
    {
        using (IDbConnection dbConnection = Connection)
        {
            dbConnection.Open();
            return dbConnection.Query<Product>("SELECT * FROM Products");
        }
    }

    public Product GetByID(int id)
    {
        using (IDbConnection dbConnection = Connection)
        {
            string sQuery = "SELECT * FROM Products"
                           + " WHERE ProductId = @Id";
            dbConnection.Open();
            return dbConnection.Query<Product>(sQuery, new { Id = id }).FirstOrDefault();
        }
    }

    public void Delete(int id)
    {
        using (IDbConnection dbConnection = Connection)
        {
            string sQuery = "DELETE FROM Products"
                         + " WHERE ProductId = @Id";
            dbConnection.Open();
            dbConnection.Execute(sQuery, new { Id = id });
        }
    }

    public void Update(Product prod)
    {
        using (IDbConnection dbConnection = Connection)
        {
            string sQuery = "UPDATE Products SET Name = @Name,"
                           + " Quantity = @Quantity, Price= @Price"
                           + " WHERE ProductId = @ProductId";
            dbConnection.Open();
            dbConnection.Execute(sQuery, prod);
        }
    }

    public void TransactionTest()
    {
        using (IDbConnection dbConnection = Connection)
        {
            string sQuery = "UPDATE Products SET Name = 'xishuai222'"
                           + " WHERE ProductId = 1";
            dbConnection.Open();
            using (var transaction = dbConnection.BeginTransaction())
            {
                dbConnection.Execute(sQuery);
                ///to do throw exception
                transaction.Commit();
            }
        }
    }
}

调用代码:

public class Program
{
    public static void Main(string[] args)
    {
        var productRepository = new ProductRepository();
        var product = new Product() { Name = "xishuai" };
        productRepository.Add(product);

        var products = productRepository.GetAll();
        foreach (var item in products)
        {
            Console.WriteLine($"id: {item.ProductId}; name: {item.Name}");
        }

        productRepository.TransactionTest();

        Console.ReadKey();
    }
}

参考资料:

posted @   田园里的蟋蟀  阅读(2408)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
历史上的今天:
2014-12-02 写点东西来吐槽一下自己,真是无语了。
点击右上角即可分享
微信分享提示