先建三层构造(DataModel、DAL、BLL)
1.在DAL层添加2个类
1.> public class CatelogDAO
{
// 查询所有的类别
public List<Catelog> Select()
{
MyDBEntities db = new MyDBEntities();
// return db.Catelog.Select(p=>p).ToList();
var result = from catelog in db.Catelog
select catelog;
return result.ToList();
}
2.> public class ArticleDAO
{
// 查询所有的文章信息
public List<Article> Select()
{
// New一个实体模型:
MyDBEntities db = new MyDBEntities();
return db.Article.Select(a=>a).ToList();
}
// 根据id查找文章
public Article Select(int id)
{
MyDBEntities db = new MyDBEntities();
return db.Article.Where(p=>p.Id==id).FirstOrDefault();
}
// 添加文章
public int Add(Article article)
{
MyDBEntities db = new MyDBEntities();
db.Article.Add(article);
db.Entry<Catelog>(article.Catelog).State = System.Data.Entity.EntityState.Unchanged;
return db.SaveChanges();
}
}
2.再在BLL层添加2个类
1.> public class ArticleService
{
private ArticleDAO adao = new ArticleDAO();
public List<Article> Select()
{
return adao.Select();
}
public Article Select(int id)
{
return adao.Select(id);
}
public int AddArticle(Article article)
{
if (String.IsNullOrEmpty(article.Title)){
throw new Exception("标题不能为空!");
}
return adao.Add(article);
}
}
2.> public class CatelogServcie
{
private CatelogDAO cdao = new CatelogDAO();
// 所有的类别
public List<Catelog> Select()
{
return cdao.Select();
}
}
3.在项目中添加一个Web窗体
根据需求给出相应的一些样式
New2个方法: CatelogServcie catelogService = new CatelogServcie();
ArticleService articleService = new ArticleService();
在加载事件中显示对应数据:
protected void Page_Load(object sender, EventArgs e)
{
string message=Request.QueryString["message"];
if(!string.IsNullOrEmpty(message))
this.Label1.Text = message;
if (!IsPostBack)
{
this.DdlCatelog.DataSource = catelogService.Select();
this.DdlCatelog.DataBind();
}
}
给一个Button控件,在双击这个控件:
protected void Button1_Click(object sender, EventArgs e)
{
Article article = new Article();
article.Title = this.TxtTitle.Text;
article.Author = this.TxtAuthor.Text;
article.Content = this.TxtContent.Text;
article.PushTime = DateTime.Now;
article.Catelog = new Catelog() { Id= int.Parse(this.DdlCatelog.SelectedValue) };
try
{
int count = articleService.AddArticle(article);
if (count > 0)
{
Response.Redirect("~/Add.aspx?message=添加成功!");
}
}
catch (Exception ex)
{
Response.Redirect("~/Add.aspx?message="+ex.Message);
}
}