前进中的蜗牛

番茄大叔

水滴穿石,非一日之功;没有量变,何来质变。

业务逻辑层-Active Record

Active Record(活动记录模式),当系统中的业务和数据库中的表存在一一对应关系的时候,可用采用。
Active Record模式的特点:每个业务对象代表数据表中的一行数据,并且业务对象还包括了数据的增删改查的方法。

ORM

一般这种模式采用一种ORM框架,即对象关系映射。这里用的的映射是:Dapper(开源轻量级,高效率,白自动化),Dapper需要我们写sql语法,所有是半自动化。

案例

内容管理系统中一博客系统

  1. 可以发布博客
  2. 对博客进行评论

code

代码下载

对象实体

	public class Post
	{
		public int Id { get; set; }
		public string Subject { get; set; }
		public string Text { get; set; }
		public DateTime DateAdded { get; set; }
	}

    public class Comment
	{
		public int? Id { get; set; }
		public string Text { get; set; }
		public string Author { get; set; }
		public DateTime DateAdded { get; set; }
		public int PostId { get; set; }
	}

实体对象

	public class PostWithComment
	{
		public int Id { get; set; }
		public string Subject { get; set; }
		public string Text { get; set; }
		public DateTime DateAdded { get; set; }
		public List<Comment> Comments { get; set; }
	}

数据连接

因Dapper是对DbConnection的扩展方法,这里定义一个父类ConnectionBase,操作数据的类只需继承父类

	public abstract class ConnectionBase
	{
		public static string ConnectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

		protected SqlConnection _connection;

		protected SqlConnection connection => _connection ?? (_connection = GetOpenConnection());

		public static SqlConnection GetOpenConnection(bool mars = false)
		{
			var cs = ConnectionString;
			if (mars)
			{
				var scsb = new SqlConnectionStringBuilder(cs)
				{
					MultipleActiveResultSets = true
				};
				cs = scsb.ConnectionString;
			}
			var connection = new SqlConnection(cs);
			connection.Open();
			return connection;
		}

		public void Dispose()
		{
			_connection?.Dispose();
		}
	}

服务

public class BlogService: ConnectionBase
	{
		public IEnumerable<Post> GetAllPosts()
		{
			string sql = "select * from Posts";
			return connection.Query<Post>(sql);
		}

		public PostWithComment GetPostWithComments(int postId)
		{
			string sql = @"select * from Posts p
							left join Comments c on p.Id = c.PostId
							where p.Id = @Id";
			PostWithComment result = null;
			var relust = connection.Query<PostWithComment, Comment, PostWithComment>(sql,(post,comment)=> 
			{
				if(result == null)
				{
					result = post;
					result.Comments = new List<Comment>();
				}
				if(comment != null)
				{
					result.Comments.Add(comment);
				}
				return result;
			},
			new { Id=postId}).FirstOrDefault();

			return relust;
		}
	}
posted @ 2018-07-31 18:35  LoveTomato  阅读(288)  评论(0编辑  收藏  举报