1、首先使用Visual Studio创建一个ASP.NET Web 应用程序(.NET Framework)
2、搭建模板将页面放入模板中,将css、js导入模板中
3、创建类库右击添加ADO.NET 实体数据库模型 选中来自数据库的EF设计器点击下一步新建连接 在服务器名称里输入localhost
身份验证选中SQL server验证 用户名和密码输入Sql server的账号密码选择你所用的数据库 点击下一步选择否 下一步选中所有的列 这样一个实体类就出来了
4、新建一个类库 右击选择EF 6.x DbContext 找到Model1.Context.tt 将下面的代码覆盖进去 将里面的引用修改为自己的
<#@ template language="C#" debug="false" hostspecific="true"#>
<#@ include file="EF.Utility.CS.ttinclude"#><#@
output extension=".cs"#>
<#
CodeGenerationTools code = new CodeGenerationTools(this);
MetadataLoader loader = new MetadataLoader(this);
CodeRegion region = new CodeRegion(this, 1);
MetadataTools ef = new MetadataTools(this);
string inputFile = @"..\\JiaHua.Permission.Model\Permission.edmx";
EdmItemCollection ItemCollection = loader.CreateEdmItemCollection(inputFile);
string namespaceName = code.VsNamespaceSuggestion();
EntityFrameworkTemplateFileManager fileManager = EntityFrameworkTemplateFileManager.Create(this);
#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JiaHua.Permission.Model;
namespace JiaHua.Permission.Repository
{
<#
foreach (EntityType entity in ItemCollection.GetItems<EntityType>().OrderBy(e => e.Name))
{
#>
public partial class <#=entity.Name#>Repository : BaseRepository<<#=entity.Name#>,PermissionEntities>
{
}
<#}#>
}
5、在数据访问层中添加两个类BaseRepository和DbContextFactory
public class BaseRepository<T, TS> where T : class, new()
where TS : DbContext, new()
{
private static DbContext Db
{
get
{
var dbContext = DbContextFactory<TS>.GetCurrentDbContext();
return dbContext;
}
}
#region 添加数据
public virtual bool Add(T entity)
{
Db.Set<T>().Add(entity);
return Db.SaveChanges() > 0;
}
public virtual bool AddRange(List<T> entities)
{
Db.Set<T>().AddRange(entities);
return Db.SaveChanges() > 0;
}
#endregion
#region 修改数据
public virtual bool Update(T entity)
{