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 WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
t_book t_Book = new t_book();
t_Book.id = "24";
t_Book.name = "单片机";
t_Book.author = "吴亮亮";
t_Book.press = "人民出版社";
t_Book.number = 10;
BookDBEntities db = new BookDBEntities();
db.t_book.Add(t_Book); //将数据添加到EF,并且添加了一个添加标记 add标记=insert
db.SaveChanges(); //执行此行代码,数据会被保存到数据库
MessageBox.Show("保存成功");
}
private void button2_Click(object sender, EventArgs e) //查询
{
BookDBEntities db = new BookDBEntities();
var vs= from u in db.t_book //link 表达式 等价于 select * from t_book where id=24
where u.id == "24"
select u;
foreach (var item in vs) //遍历的时候,才连接数据库,从数据中取数据。数据用到的时候才去数据库取数据,不用不查询
{
Console.WriteLine(item.name);
}
}
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码已从模板生成。
//
// 手动更改此文件可能导致应用程序出现意外的行为。
// 如果重新生成代码,将覆盖对此文件的手动更改。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApp1
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class BookDBEntities : DbContext
{
public BookDBEntities()
: base("name=BookDBEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<t_book> t_book { get; set; }
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码已从模板生成。
//
// 手动更改此文件可能导致应用程序出现意外的行为。
// 如果重新生成代码,将覆盖对此文件的手动更改。
// </auto-generated>
//------------------------------------------------------------------------------
namespace WindowsFormsApp1
{
using System;
using System.Collections.Generic;
public partial class t_book
{
public string id { get; set; }
public string name { get; set; }
public string author { get; set; }
public string press { get; set; }
public Nullable<int> number { get; set; }
}
}