在开始之前,先声明一下,写本系列教程是参照 韩迎龙(Kencery)http://www.cnblogs.com/hanyinglong/category/399820.html 的博客,然后把我的思想融入到这个框架中,如有任何版权问题请给我留言。 切入正题,这一章主要介绍Model层的设计,用的是EntityFrame
在开始之前,先声明一下,写本系列教程是参照
韩迎龙(Kencery)http://www.cnblogs.com/hanyinglong/category/399820.html 的博客,然后把我的思想融入到这个框架中,如有任何版权问题请给我留言。
切入正题,这一章主要介绍Model层的设计,用的是EntityFramework,由于项目初期可能数据库字段经常发生改变,所以用的是CodeFirst。
在Model项目中新建User类,内容如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Pwd { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Model
{
public class Role
{
public int Id { get; set; }
public int RoleValue { get; set; }
public string RoleName { get; set; }
}
}暂时这两个类的字段定义如此,随着项目的完善,这两个类的字段会有所变化。
现在,该是EntityFramework出场的时候了,
一.建立数据库上下文类(在Model类库中建立HelloMVCDataContext.cs),我理解数据库上下文就是,把数据库的所有表映射到这个类中,操作这个类就像操作数据库字段一样。具体代码如下
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
namespace Model
{
public class HelloMVCDataContext : DbContext
{
public DbSet<User> UserDb { get; set; }
public DbSet<Role> RoleDb { get; set; }
}
}二.在Web.config中配置数据库上下文的连接字符串,具体如下:
<connectionStrings>
<add name="HelloMVCDataContext"
connectionString="Data Source=(LocalDb)\v11.0;
Initial Catalog=HelloMVCDataContext;
Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\HelloMVCDataContext.mdf"
providerName="System.Data.SqlClient" />
</connectionStrings>public ActionResult Index()
{
Model.HelloMVCDataContext db = new Model.HelloMVCDataContext();
db.RoleDb.ToList();
ViewBag.Message = "修改此模板以快速启动你的 ASP.NET MVC 应用程序。";
return View();
}今天的CodeFirst就暂时到这里,下一章会讲解IDAL和DAL层。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号