目标:使用EF Code First模式生成数据库,并使用三层架构设计简单的登录程序。
1.首先来看一下三层架构最后的结构:
2.三层架构主要由UI层、BLL层以及DAL层和Model实体构成
UI层主要是作为登录界面的设计层:
BLL层(业务逻辑层)主要是负责搭建起UI界面层与DAL数据访问层之间的桥梁,通过UI层向BLL层发起请求,BLL层再向DAL层发起请求,DAL层与数据实体进行访问,将数据逐级返回至UI层。
UI↔BLL↔DAL
↖ ↑ ↗
Model
各层之间的引用关系:
DAL层引用Model层
BLL层引用DAL层和Model层
UI层引用BLL层和Model层
3.新建一个winfrom项目,并命名为ThreeLayers.UI作为UI层
4.设计一个简单的登录界面(为方便体现code first模式,添加用户直接使用code first模式实现生成表并添加):
5.向解决方案中添加多个类库项目,并命名为各个层的名字
6.使用Code First模式编写Users.cs以及UsersEntities.cs用于生成数据表、添加用户
使用code first生成需要引用Entity Framework,在Nuget程序包里搜索并安装(需要联网下载)
安装完成后,在Users.cs里添加如下代码,用于生成数据表的账号、密码字段
using System.ComponentModel.DataAnnotations;
namespace ThreeLayers.Model
{
public class Users
{
[Key]
public int id { get; set; }//ID
public string username { get; set; }//账号
public string password { get; set; }//密码
}
}
打开UsersEntity.cs添加如下代码,用于添加数据库实体与代码的映射,在数据库中生成User表
using System.Data.Entity;
namespace ThreeLayers.Model
{
public class UsersEntities : DbContext //继承DbContext
{
public UsersEntities() :
base("name=ConnCodeFirst") //用于在App.config中配置连接数据库的信息
{
}
public DbSet<Users> Users { get; set; } //添加映射
}
}
7.设计Model实体
Model.cs代码如下,主要是用于各个层之间字段的相互调用
namespace ThreeLayers.Model
{
public class UserInfo
{
private string _username;
private string _pswd;
public string username
{
set { _username = value; }
get { return _username; }
}
public string pswd
{
set { _pswd = value; }
get { return _pswd; }
}
}
}
8.设计DAL层,用于与数据库之间的交互
添加对Model的引用
以及System.Configuration用于在使用App.config中的连接字符串
在DBbase.cs中添加代码如下,主要用于数据库的连接、查询
using System.Data;
using System.Data.SqlClient;
namespace ThreeLayers.DAL
{
public class DBbase
{
//读取配置文件 连接数据库语句
public static string strCon = System.Configuration.ConfigurationManager.ConnectionStrings["ConnCodeFirst"].ConnectionString;
//public static string strCon = "Data Source=.;Initial Catalog=threeLayer;Persist Security Info=True;User ID=sa;Password=123";
//实例化连接对象 con
SqlConnection con = new SqlConnection(strCon);
//检测连接是否打开
public void ChkConnection()
{
if (this.con.State == ConnectionState.Closed)
{
this.con.Open();
}
}
//执行语句,返回该语句查询的数据行的总数
public int RowCount(string strSQL)
{
ChkConnection();
try
{
SqlDataAdapter da = new SqlDataAdapter(strSQL, con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0].Rows.Count;
}
catch
{
return 0;
}
}
}
}
在UserAccess.cs中添加代码如下,用于BLL层通过DAL访问数据库
using ThreeLayers.Model;
namespace ThreeLayers.DAL
{
public class UserAccess
{
DBbase db = new DBbase();
//用户登录的方法
public int UserLogin(UserInfo user)
{
string strsql = "select * from users where username = '" + user.username + "' and password = '" + user.pswd + "'";//通过实体中的属性访问
return db.RowCount(strsql);
}
}
}
9.设计BLL层用于UI层与DAL层之间的交互
在UserAccess.cs中添加代码如下
namespace ThreeLayers.BLL
{
public class UserAccess
{
DAL.UserAccess d_userAccess = new DAL.UserAccess();
public bool UserLogin(Model.UserInfo m_userInfo)//用于判断登录是否成功
{
if (d_userAccess.UserLogin(m_userInfo) > 0)
return true;
else
return false;
}
}
10.设计UI层
UI层添加并命名控件、添加对Model、BLL层的引用以及在UI项目中安装EntityFramework
界面层代码如下
using System;
using System.Windows.Forms;
using ThreeLayers.Model;
using ThreeLayers.BLL;
namespace ThreeLayers.UI
{
public partial class Form1 : Form
{
public Form1()
{
UsersEntities dbContext = new UsersEntities();
dbContext.Database.CreateIfNotExists();//不存在的情况下会创建对应的数据库
InitializeComponent();
}
UserAccess ua = new UserAccess();
UserInfo u = new UserInfo();
private void btnCreate_Click(object sender, EventArgs e)
{
using (var data = new UsersEntities())//向数据表中添加用户
{
var user1 = data.Users.Create();
user1.username = txtAccount.Text;
user1.password = txtPswd.Text;
data.Users.Add(user1);
data.SaveChanges();
}
}
private void btnLog_Click(object sender, EventArgs e)
{
u.username = txtAccount.Text;
u.pswd = txtPswd.Text;
if (ua.UserLogin(u))
MessageBox.Show("登录成功!");
else
MessageBox.Show("登录失败!");
}
}
}
在App.config中添加连接数据库字符串(根据实际数据库自行配置)
<connectionStrings>
<add name="ConnCodeFirst" connectionString="server=SNOWICE;uid=sa;pwd=520000;database=CodeFirstDemoDb" providerName="System.Data.SqlClient"/>
</connectionStrings>
11.运行,第一次运行可能要久一些,因为第一次创建数据库
成功运行之后在数据库的对象资源管理器中(小编用的是SQL Server Management Studio)可以看到数据库、数据表已经创建
随便输入一个账号密码,点击登录
登录失败,因为数据表中没有数据
点击添加用户,之后登录,提示登录成功
查询数据表,发现已经添加进去
以上便是针对三层架构以及Code First模式设计的一个简单的登录程序,本身小编也是初学该架构及设计模式,可能有很多错误,希望大家指正。
注:有些代码从网上其他大神那里参考,只是一个小Demo所以请大家多多包涵!
附源代码连接:http://download.csdn.net/download/qq_16514611/9770371