MVC EF 修改 封装类 通用泛型方法(一)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity.Infrastructure;
using System.Data.Entity; namespace DAL
{
public class EF_Help
{
DbContext db; //数据上下文
/// <summary>
/// 修改 个别 数据
/// </summary>
/// <param name="model">要修改的实体对象</param>
/// <param name="proNames">要修改的 属性 名称</param>
/// <returns></returns>
public int Modify<T>(T model, params string[] proNames) where T : class
{
DbEntityEntry entry = db.Entry<T>(model);
entry.State = EntityState.Unchanged;
foreach (string proName in proNames)
{
entry.Property(proName).IsModified = true;
}
db.Configuration.ValidateOnSaveEnabled = false;
return db.SaveChanges();
} /// <summary>
/// 修改 多数 数据, 个别数据除外,proNames 不写 则是 修改全部
/// </summary>
/// <param name="model">要修改的实体对象</param>
/// <param name="proNames">不需要要修改的 属性 名称</param>
/// <returns></returns>
public int ModifyWithOutproNames<T>(T model, string prymartKey, params string[] proNames) where T : class
{ DbEntityEntry entry = db.Entry<T>(model);
entry.State = EntityState.Unchanged;
var properties = model.GetType().GetProperties();
for (int i = ; i < properties.Length; i++)
{
if (properties[i].PropertyType.Name.Contains("ICollection")
|| properties[i].Name == prymartKey
|| proNames.Contains(properties[i].Name)) continue;// 排除 外面 主键 proNames
entry.Property(properties[i].Name).IsModified = true;
}
db.Configuration.ValidateOnSaveEnabled = false;
return db.SaveChanges();
} public EF_Help(DbContext dbContext)
{
db = dbContext;
}
}
}

调用:

using System;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using KT_Product_Show_Market.Areas.Account.Models;
using Newtonsoft.Json;
using EntityFramework.Extensions;
using System.Collections; namespace KT_Product_Show_Market.Areas.Account.Controllers
{
public class UserController : Controller
{
public UserController()
{
ef_Help = new DAL.EF_Help(db);
}
KT_Product_MarketEntities db = new KT_Product_MarketEntities();
DAL.Custom_Expression CE = new DAL.Custom_Expression();
DAL.EF_Help ef_Help; [HttpPost]
[ActionName("Edit")]
public int Edit_Post(TraderInfo post_model)
{
int Temp = ;
if (string.IsNullOrEmpty(post_model.LoginPassward))
{
Temp = ef_Help.ModifyWithOutproNames<TraderInfo>(post_model, "LoginPassward");
}
else
{
Temp = ef_Help.ModifyWithOutproNames<TraderInfo>(post_model);
}
return Temp;
}
}
}

MVC EF 修改  封装类 通用泛型方法(一)

前台 不显示   实际密码,点击 修改密码 ,显示 文本框,然后就可以设置新密码了。

后台如果 有接收 密码,则执行 ef_Help.ModifyWithOutproNames<TraderInfo>(post_model, "LoginPassward");   除了LoginPassward  以外的列 都会修改。

如果没有 接收到密码 就 执行 ef_Help.ModifyWithOutproNames<TraderInfo>(post_model);  修改所有列

上一篇:【编程工具】Sublime Text3的安装和常用插件推荐


下一篇:go语言开发工具sublime text3 + gosublime配置