EntityFramework数据持久化-多表查询、添加
目的:实现简单的EF查询和添加
工具:Sql Server; Visual Studio 2017
一.Sql数据库、表的创建
创建 Catelog 类别表
字段名 | 说明 |
---|---|
id | 编号 |
name | 类别名称 |
comment | 类别说明 |
添加数据
创建 Aritcle 文章表
字段名 | 说明 |
---|---|
id | 编号 |
title | 文章标题 |
author | 作者 |
content | 文章内容 |
catelogid | 外键 类型id |
添加数据
二.EF模型的建立及代码的编写
- 打开vs创建ASP.Net Web 应用程序(.NET Framework)
- 添加-引用-搜索linq(程序集)-全都勾选
- 创建ADO.NET 实体数据模型
*d.创建web窗体
在 .aspx文件中添加以下代码
<body>
<form id="form1" runat="server">
<div>
<table border="1">
<tr>
<th>文章名字</th>
<th>作者</th>
<th>介绍</th>
<th>文章类型</th>
</tr>
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<tr>
<td><%# Eval("title") %></td>
<td><%# Eval("author") %></td>
<td><%# Eval("content") %></td>
<td><%# Eval("CatelogName") %> </td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<asp:Button ID="Button1" runat="server" Text="添加" OnClick="Button1_Click" />
</div>
</form>
</body>
效果图
在 .aspx.cs文件中添加
- 选择button
- 右下角属性点击闪电标
- 双击click
protected void Page_Load(object sender, EventArgs e)
{
MyDBEntities1 my = new MyDBEntities1();
var result = from art in my.Aritcle
join Catelog in my.Catelog on art.catelogid equals Catelog.id
select new
{
Title = art.title,
Author = art.author,
Content = art.content,
CatelogName = Catelog.name
};
this.Repeater1.DataSource = result.ToList();
this.Repeater1.DataBind();
}
protected void Button1_Click(object sender, EventArgs e)
{
MyDBEntities1 my = new MyDBEntities1();
Aritcle art = new Aritcle();
art.id = 4;
art.title = "de下雨了";
art.author = "de黄少天";
art.content = "de好烦";
art.catelogid = 2;
art.Catelog = new Catelog() { id = 5 };
my.Aritcle.Add(art);
my.SaveChanges();
Catelog cat = new Catelog();
//cat.id = 3;
cat.name = "魔幻";
cat.comment = "啦啦啦啦啦啦啦";
my.Catelog.Add(cat);
int count = my.SaveChanges();
if (count >= 0)
{
Response.Write("添加成功");
}
收工 然后就能运行了
ps:还有不会的请来骚扰我,来者不拒哦