.NET E F(Entity Framework)框架 DataBase First 和 Code First 简单用法。

    EF是微软.NET平台官方的ORM(objet-relation mapping),就是一种对象-关系 映射,是将关系数据库种的业务数据用对象的形式表现出来,并通过面向对象的方式讲这些对象组织起来,实现系统业务逻辑的过程。

DataBase First 开发方式

DataBase First 又叫数据库优先的开发方式,是一种比较旧的开发方式,现在越来越多的企业已经不再使用这种开发方式了。当然,对于一些旧项目进行升级,在已经有了数据库的情况下,使用此方式是十分方便的。

使用方法

(1)在项目中右键添加新项,找到ADO.NE实体数据库模型(在c#项下的数据里面)。

下一步

实现增删改查

代码如下

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace mvc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

BooksEntities db = new BooksEntities();
private void Form1_Load(object sender, EventArgs e)
{
//dataGridView1.DataSource = db.Management.ToList();
//默认第一页
label2.Text = "1";
//初始化下拉列表
PageSize();
//获取每页显示数据条数
int pagesize = Convert.ToInt32(comboBox1.SelectedItem);
//获取数据总数
int count = db.Management.Count();
BinData(pagesize, count, x => x.图书编号 > 0);

}

//查询.排序
bool isClick = false;//判断查询按钮是否点击
Management book = new Management();//新建数据实体对象
//定义一个BinData方法连接数据
private void BinData(int pagesize, int count, Expression<Func<Management, bool>> where)
{
dataGridView1.DataSource = null;
//dataGridView1.AutoGenerateColumns = false;//自动创建列  或者关闭自动手动添加
//获取总页数
int pagecount = Convert.ToInt32(Math.Ceiling(count * 1.0 / pagesize));
label3.Text = pagecount.ToString();
//当前页面
int currentpage = Convert.ToInt32(label2.Text);
//查询、排序
dataGridView1.DataSource = GetPagedList<int>(currentpage, pagesize, where, x => x.图书编号);
btnfirst.Enabled = true;
btnpre.Enabled = true;
btnnext.Enabled = true;
btnlast.Enabled = true;
//当前页为第一页时,首页,上一页按钮不能点击,当前页为尾页时,下一页按钮不能点击,当数据
//用一页就可以显示完成,禁用首页,上一页,下一页,尾页按钮
if (currentpage == 1 && count <= pagesize)
{
btnfirst.Enabled = false;
btnpre.Enabled = false;
btnnext.Enabled = false;
btnlast.Enabled = false;
}
else if (currentpage == 1)
{
btnfirst.Enabled = false;
btnpre.Enabled = false;
}
else if (currentpage == pagecount)
{
btnnext.Enabled = false;
btnlast.Enabled = false;
}
}
//初始化每页显示的数据条数
private void PageSize()
{
comboBox1.Items.Clear();
comboBox1.Items.AddRange(new string[] { "5", "10", "50", "100" });
comboBox1.SelectedIndex = 0;
}
//获取分页列表方法
public List<Management> GetPagedList<Tkey>(int currentpag, int pagesize, Expression<Func<Management, bool>> where, Expression<Func<Management, Tkey>> orderBy)
{
return db.Management.Where(where).OrderBy(orderBy).Skip((currentpag - 1) * pagesize).Take(pagesize).ToList();
}
private void isCondition()
{
if (!string.IsNullOrEmpty(textBox1.Text.Trim()) && isClick)
{
BinData(Convert.ToInt32(comboBox1.SelectedItem), db.Management.Where(x => x.书名.Contains(textBox1.Text.Trim())).Count(), x => x.书名.Contains(textBox1.Text.Trim()));
}
else
{
BinData(Convert.ToInt32(comboBox1.SelectedItem), db.Management.Count(), x => x.图书编号 > 0);
}
}
private void button4_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() != null)
{
dataGridView1.DataSource = db.Management.Where(x => x.书名.Contains(textBox1.Text.Trim())).ToList();
}
else
{
Form1_Load(null, null);
}

}

private void button1_Click(object sender, EventArgs e)
{
insert insertfrom = new insert();
insertfrom.Show();
}


private void button3_Click(object sender, EventArgs e)
{
int id = Convert.ToInt32(dataGridView1.CurrentRow.Cells["图书编号"].Value);
if (MessageBox.Show("您确定要删除么?", "提示消息", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
Management book = db.Management.FirstOrDefault(x => x.图书编号 == id);
if (book != null)
{
db.Management.Remove(book);
db.SaveChanges();
MessageBox.Show("删除成功!");
Form1_Load(null, null);
}
}
}

private void button5_Click(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
Management book = new Management()
{
书名 = "天龙八部" + i,
作者 = "金庸",
单价 = 1 + i
};
db.Management.Add(book);

}
db.SaveChanges();
Form1_Load(null, null);
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
label2.Text = "1";
isCondition();
}


private void btnfirst_Click(object sender, EventArgs e)
{
label2.Text = "1";
isCondition();
}

private void btnpre_Click(object sender, EventArgs e)
{
label2.Text = (Convert.ToInt32(label2.Text)-1).ToString();
isCondition();
}

private void btnnext_Click(object sender, EventArgs e)
{
label2.Text = (Convert.ToInt32(label2.Text) + 1).ToString();
isCondition();
}

private void btnlast_Click(object sender, EventArgs e)
{
label2.Text = label3.Text;
isCondition();
}
}
}

 

以上代码不懂得欢迎评论。(我会经常看的)

以上代码比较难理解的就是可以把lambda表达式做为参数,这是一个比较通用的方法。

 

 

CodeFirst

CodeFirst开发方式又叫做代码优先,是用代码创建数据库。EF提供了通过类型的结构推断生成SQL并创建数据库种的表,而且能够通过类型的成员推断出实体间的关系,我们只需要编写实体类就可以进行EF数据库开发:

如果你已经有EF框架

可以右键 引用,添加新项找到添加引用

没有的话右键管理NuGet程序包

找到EF框架安装。

在项目中添加BookDB类(数据库)和Book类(表) 代码如下:

 

BookDB(自动迁移版本)

 

using ByzkApi.Models.ByApiTable;
using ByzkApi.Util;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ByzkApi.Models
{
    public class ByApiDB : DbContext//内存上下文可以理解为内存数据库
    {

        public ByApiDB() : base(ConfigHelper.GetConnectionString("Basedb"))
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<ByApiDB, ConfigurationS>());
        }
        //默认生成的表名为类型的复数
        //public DbSet<Book> book { get; set; }

        //public DbSet<ByApiTable.Users> Users { get; set; }

        //public DbSet<ByApiTable.Account> Accounts { get; set; }


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //base.OnModelCreating(modelBuilder);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
        public class ConfigurationS : DbMigrationsConfiguration<ByApiDB>
        {
            public ConfigurationS()
            {
                // 开启自动迁移
                AutomaticMigrationsEnabled = true;
                //迁移的时候是否允许数据丢失
                AutomaticMigrationDataLossAllowed = true;

            }
        }

    }
}

 

 

Book

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace codefirst
{
public class Book
{
public int BookID { get; set; }
public string BookName { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
}

 

代码优先,需要配置一下App.config文件

<connectionStrings>
<add name="BookDB" connectionString="server=.;uid=sa;pwd=macong123.;database=BookDB" providerName="System.Data.SqlClient"/>
</connectionStrings>

 

EF约定


表名后面会自动加s(复数形式)

ID列或类名+ID列约定为主键,int类型的主键约定为自增长(从1开始)。

属性名为类名,约定为导航属性(对应数据库中的关系)。

 

一般的集合或者数组都实现了IEnumberable

 

EF并不是万能的,有些特殊的SQL语句还是需要直接查询。

用法可以百度 :EF中执行SQL

最后欢迎观看CoolDog的博客园。

 

posted @ 2017-12-07 11:15  CoolDog;  阅读(523)  评论(0编辑  收藏  举报