ASP.Net EF架构

类别

/// <summary>
/// 用户类
/// </summary>
[Table("TB_User")]
public class UserModel
{
[Key]
public int UId { get; set; }
public int UName { get; set; }
[ForeignKey("UserLevel")]
public int LevelId { get; set; }
public UserLevelModel UserLevel { get; set; }
}

/// <summary>
/// 用户级别类
/// </summary>
[Table("TB_UserLevel")]
public class UserLevelModel
{
[Key]
public int LId { get; set; }
public string LName { get; set; }
public int Level { get; set; }
}

CONTEXT

using System;
using System.Data.Entity;
using System.Linq;
using G6.EFTest.Models;
public class MyContext : DbContext
{
//您的上下文已配置为从您的应用程序的配置文件(App.config 或 Web.config)
//使用“MyContext”连接字符串。默认情况下,此连接字符串针对您的 LocalDb 实例上的
//“G6.EFTest.DALS.MyContext”数据库。
//
//如果您想要针对其他数据库和/或数据库提供程序,请在应用程序配置文件中修改“MyContext”
//连接字符串。
public MyContext()
: base("name=MyContext")
{
}
//为您要在模型中包含的每种实体类型都添加 DbSet。有关配置和使用 Code First 模型
//的详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=390109。
public DbSet<UserModel> Users { get; set; }
public DbSet<UserLevelModel> UserLevels { get; set; }
}
//public class MyEntity
//{
// public int Id { get; set; }
// public string Name { get; set; }
//}
}

 

EFDBHELPER

public class EFHelper<T> where T:class,new()
{
MyContext db = new MyContext();//实例化上下文对象
/// <summary>
/// 添加
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public int Insert(T t)
{
db.Set<T>().Add(t);
return db.SaveChanges();
}
/// <summary>
/// 修改
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public int Modify(T t)
{
db.Set<T>().Attach(t);
db.Entry<T>(t).State = EntityState.Modified;
return db.SaveChanges();
}
/// <summary>
/// 删除
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public int Delete(int id)
{
var obj = db.Set<T>().Find(id);//直接通过find方法和id找到对应的实体信息
db.Set<T>().Remove(obj);
return db.SaveChanges();
}
/// <summary>
/// 显示查询
/// </summary>
/// <returns></returns>
public DbSet<T> Show()
{
return db.Set<T>();
}
/// <summary>
/// 通用的批删
/// </summary>
/// <param name="ids"></param>
/// <returns></returns>
public int Dels(string ids)
{
Type type = typeof(T);
PropertyInfo[] pros = type.GetProperties();
string sql = $"delete from TB_{type.Name.Replace("Model","")} where {pros[0].Name} in ({ids})";
return db.Database.ExecuteSqlCommand(sql);
}
}

控制器

EFHelper<UserModel> _userDAL = new EFHelper<UserModel>();
EFHelper<UserLevelModel> _userLevelDAL = new EFHelper<UserLevelModel>();
[HttpGet]
public IHttpActionResult Show()
{
var linq = from u in _userDAL.Show().AsEnumerable()
join e in _userLevelDAL.Show().AsEnumerable() on u.LevelId equals e.LId
select new UserModel()
{
LevelId = u.LevelId,
UId = u.UId,
UName = u.UName,
UserLevel = new UserLevelModel()
{
Level = e.Level,
LId = e.LId,
LName = e.LName
}
};
return Ok(linq.ToList());
}

 

ASP.Net EF架构

上一篇:TCP和HTTP


下一篇:ASP.Net 邮箱发送