一、建立数据库和数据表
1.建立数据库(MyDB),并建立文章表(Article)和类型表(Cate)
2.数据表要求如下:
文章表(Article)
列名 | 要求 | 备注 |
---|---|---|
Id | int | 主键,自增 |
Title | vachar(50) | |
Author | vachar(50) | |
CateId | int |
类型表(Cate)
列名 | 要求 | 备注 |
---|---|---|
Id | int | 主键,自增 |
Name | vachar(50) | |
Comment | text |
二、创建web项目
1.新建后缀名为.aspx的页面
2.加入Repeater控件和button控件
3.在button控件的点击事件里输入以下内容
4.在Page_Load事件里输入以下内容
//button点击事件
protected void Button2_Click(object sender, EventArgs e)
{
MyDBEntities1 db = new MyDBEntities1();
//同时加两个表
Article art = new Article();
art.Title = txttitle.Text;
art.Content = txtcontent.Text;
art.Author = txtauthor.Text;
//article.Catelogid = 1;
art.Catelog = new Catelog { Name = txtcatelog.Text, Content = txtcatecontent.Text };
db.Article.Add(art);
db.SaveChanges();
int count = db.SaveChanges();
if (count >= 0)
{
Response.Write("添加成功");
var result = from article in db.Article
join catelog in db.Catelog on article.Catelogid equals catelog.Id
select new { Title = article.Title, Author = article.Author, Content = article.Content, Catelogid = catelog.Name };
this.Repeater1.DataSource = result.ToList();
this.Repeater1.DataBind();
}
//Page_Load加载事件
protected void Page_Load(object sender, EventArgs e)
{
MyDBEntities1 db = new MyDBEntities1();
var result = from article in db.Article
join catelog in db.Catelog on article.Catelogid equals catelog.Id
select new { Title = article.Title, Author = article.Author, Content = article.Content, Catelogid = catelog.Name };
this.Repeater1.DataSource = result.ToList();
this.Repeater1.DataBind();
}
这样,我们的EntityFramwork查询就完成了.