创建项目,EF配置,数据访问层搭建请访问:
C#窗体基于三层架构使用EntityFramework作为数据访问层,依据Code First原则【一】
按教程完成后,我们继续。
一、在视图层新建窗体,命名test.cs
窗体布局如下:
二、在BLL层新建testManage.cs
继续添加运货商查询数据的方法
EFHelper<运货商> nor = new EFHelper<运货商>();
public List<运货商> GetList(string str)
{
return nor.getSearchList(item=>item.公司名称.Contains(str)).ToList();
}
常用的Lambda表达式有以下:
//模糊查询运货商表公司名称列包含str的数据,相当于SQL的 %str%
nor.getSearchList(item => item.公司名称.Contains(str));
//查询运货商表公司名称列等于str的数据,相当于SQL的 运营商.公司名称==str
nor.getSearchList(item => item.公司名称.Equals(str));
//查询运货商表运货商ID列大于等于0的数据,相当于SQL的 运营商.运货商ID>=0(查询所有记录)
nor.getSearchList(item => item.运货商ID >= 0);
在视图层test.cs窗体文件中,编写代码
testManage nor = new testManage();
//查询按钮的点击事件
private void btnSubmit_Click(object sender, EventArgs e)
{
string strInput = txtinput.Text;
dataGridView1.DataSource = nor.GetList(strInput);
}
using NorthwindCNShop.BLL;
using NorthwindCNShop.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace NorthwindCNShop
{
public partial class test : Form
{
testManage nor = new testManage();
public test()
{
InitializeComponent();
}
private void test_Load(object sender, EventArgs e)
{
}
//查询按钮的点击事件
private void btnSubmit_Click(object sender, EventArgs e)
{
string strInput = txtinput.Text;
dataGridView1.DataSource = nor.GetList(strInput);
}
}
}
查询功能就做出来了,运行test.cs窗体,点击查询按钮,查询数据库中的数据。
我们接着做增加功能,在BLL层testManege.cs文件中写增加的方法。
public int DataAdd(运货商 param)
{
//增加成功返回1
return nor.add(param);
}
在视图层中的test.cs的“新增”按钮点击事件中编写以下代码
private void btnAdd_Click(object sender, EventArgs e)
{
//定义 运货商对象
运货商 t = new 运货商();
//输入框获取数据赋值给该对象
t.公司名称 = txtName.