1、MVC使用公用脚本
新建一个视图,将脚本代码加入,然后调用页面加入如下代码
@Html.Partial("~/Views/UserSectionView/Common.cshtml")
2、绑定下拉框值DropDownListFor下拉框默认值,注意ViewBag.TempType的TempType名称不能和m.MyType一样,不然不显示选中值
前端 @Html.DropDownListFor(m => m.MyType, ViewBag.TempType as SelectList, new { @class = "form-control" }) 后台代码 string defaultValue="123";//默认值 string[] myTypes=new string[]{"123","234"}; List<SelectListItem> typeList = new List<SelectListItem>(); if (myTypes.Length > 0) { foreach (string item in myTypes) { if (defaultValue == item) typeList.Add(new SelectListItem { Text = item, Value = item, Selected = true }); else typeList.Add(new SelectListItem { Text = item, Value = item }); } } ViewBag.TempType = new SelectList(typeList, "Value", "Text");
3、async/await异步方法如果方法返回值为空,类型填写Task,不是void
private async Task InitType(Model model)
{
}
4、查看Entityframework提示的详细错误信息
try { await scope.SaveChangesAsync(); } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { //简写 var validerr = ex.EntityValidationErrors.First().ValidationErrors.First(); Console.WriteLine(validerr.PropertyName + ":" + validerr.ErrorMessage); } return entity.Id;
5、mvc后台传递html标签到前台不进行编码通过@Html.Raw()
6、EntityFramework 实体属性值更新https://q.cnblogs.com/q/103473/
更新时不能使用Include包含被更新的对象,也不能将更新的对象属性设置为virtual,virtual效果和Include相似
using (var scope = _dbContextScopeFactory.Create()) { var db = scope.DbContexts.Get<QNetContext>(); var entity = db.ProductInfos.Find(dto.Id); dto.IsOpen = entity.IsOpen; dto.ProductId = entity.ProductId; dto.CreateUser = entity.CreateUser; _mapper.Map(dto, entity); entity.MarkModify(); entity.ProductClass = await db.ProductClasss.FirstOrDefaultAsync(p => p.Id == dto.ProductClassId);//此处不能用FindAsync,不然不能更新,提示属性名称不能为空 await scope.SaveChangesAsync(); return true; }
Find方法 :之前一直使用lambda查询(where,FirstOrDefault),有一个问题就是不管我们要查询的实体是否被dbconext缓存,都会去查询数据库,而使用Find通过主键来查询,会首先在EF Context中查找是否有被缓存过的实体,如果查找不到才去数据库查找
7、EF对象或对象集合属性加上virtual修饰后,属性值会在查询时一并加载出来,而不需要Include
8、EF在查询的字段里面包含指定对象的字段,就不需要Include指定的对象,如下
var query = db.Orders.Where(item => !item.IsDelete);
return db.Select(item => new PriceLogDto{
Id = item.Id,
UId = new UserDto(){ }
});在Orders后面就不需要包含UId对象或 if(query.UId.Name=="admin")也不需要包含对象
9、EF设置执行命令超时时间
var db = scope.DbContexts.Get<QNetContext>();
db.Database.CommandTimeout = 180;//等待3分钟
10、MVC增删改防止CSRF攻击方法
(1)、在Html表单里面使用了@Html.AntiForgeryToken()就可以阻止CSRF攻击。
(2)、相应的我们要在Controller中也要加入[ValidateAntiForgeryToken]过滤特性。该特性表示检测服务器请求是否被篡改。注意:该特性只能用于post请求,get请求无效。
参考:https://www.cnblogs.com/freeliver54/p/3620877.html
https://blog.csdn.net/cpytiger/article/details/8781457
11、EF类型转换
System.Data.Objects.EntityFunctions和System.Data.Objects.SqlClient.SqlFunctions中的方法进行比较,如下
where System.Data.Objects.SqlClient.SqlFunctions.DateDiff("s",DateTime.Now,u.Time)>0
where System.Data.Objects.EntityFunctions.DiffSeconds(DateTime.Now,u.Time)>0
12、同步方法中获取异步方法(await)返回结果
ISystemParameterService systemParameterService = DependencyResolver.Current.GetService<ISystemParameterService>(); SystemParameterDto systemParam = Task.Run(async () => await systemParameterService.FindByName(name)).ConfigureAwait(false).GetAwaiter().GetResult(); if (systemParam != null) { valueStr = systemParam.Values; systemParamDic.Add(name, valueStr); }
13、JS常用
JSON.parse(jsonstr); //可以将json字符串转换成json对象
JSON.stringify(jsonobj); //可以将json对象转换成json对符串
14、EF分页时注意问题
(1)、在表数据量比较大的时候,尽量不要用多表联查,应该在获取到分页结果后,在后台代码里面再查询其它对象的结果,可以加快查找速度,如下
PagedResult<PriceLogDto> resultList = await query.OrderByCustom(filters.sidx, filters.sord).AsNoTracking()// .Select(item => new PriceLogDto { Id = item.Id, UId = new UserDto() { Id = item.UId.Id, //UserId = item.UId.UserId,//不要查询其它表的值,会造成大量查找开销 //UserName = item.UId.UserName, //RealName = item.UId.RealName }, OrderUId = new UserDto() { Id = item.OrderUId != null ? item.OrderUId.Id : string.Empty, //UserId = item.OrderUId != null ? item.OrderUId.UserId : 0, //UserName = item.OrderUId != null ? item.OrderUId.UserName : string.Empty, //RealName = item.OrderUId != null ? item.OrderUId.RealName : string.Empty }, OrderId = item.OrderId, Type = item.Type, AmountOfChange = item.AmountOfChange, Title = item.Title, Remark = item.Remark, NowUserMoney = item.NowUserMoney, CreateDateTime = item.CreateDateTime, CreateUser = item.CreateUser, //CreateUserName = item.CreateUser != null ? db.Users.Where(u => u.Id == item.CreateUser).Select(u => u.UserName).FirstOrDefault() : "-", Rebate = item.Rebate, Feerebate = item.Feerebate }).PagingAsync(filters.page, filters.rows); //对分页数据单独进行查询,可以减少索引查找开销 foreach (var item in resultList.rows) { item.UId = db.Users.Where(u => u.Id == item.UId.Id).Select(u => new UserDto() { Id = u.Id, UserId = u.UserId, UserName = u.UserName, RealName = u.RealName }).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(item.OrderUId.Id)) { UserDto orderUId = db.Users.Where(u => u.Id == item.OrderUId.Id).Select(u => new UserDto() { Id = u.Id, UserId = u.UserId, UserName = u.UserName, RealName = u.RealName }).FirstOrDefault(); if (orderUId == null) { item.OrderUId.UserId = 0; item.OrderUId.UserName = string.Empty; item.OrderUId.RealName = string.Empty; } } }
(2)、在根据字段进行排序时,如时间字段CreateTime desc,在CreateTime前加入主键字段,可以极大的提高查询速度,如Id desc,CreateTime desc
15、解决vs编译时提示对路径bin\roslyn..的访问被拒绝错误
在NuGet中找到Microsoft.CodeDom.Providers.NotNetCompilerPlatform升级到1.0.7以上即可
16、VS2017在网站上-》右键-》属性-》Web选项卡中创建其它虚拟目录后,导致网站css加载显示不正常,删除其它虚拟目录办法
解决方案根目录-》.vs-》config-》applicationhost.config-》找到<sites>节点,里面有其它虚拟目录配置,删除保存即可。
17、MVC模型验证Remote取多个字段
[Remote("IsExists", "User", AdditionalFields = "Id", ErrorMessage = Message.Exists)]
[Remote("IsExists", "Area", AdditionalFields = "Id,ParentId", ErrorMessage = Message.Exists)]
AdditionalFields列举的字段是区分大小写的。
18、OnActionExecuting和 OnAuthorization
执行顺序,OnAuthorization在AuthorizeAttribute特性种,
先执行OnAuthorization,然后执行AuthorizeCore函数;
OnActionExecuting方法在ActionFilterAttribute特性中,
同时存在OnAuthorization和OnActionExecuting,在授权检查完毕之后执行OnActionExecuting,也就是说OnActionExecuting后执行
19、MVC的WebAPI接口,如果接口方法名使用Get开头,如GetUserDetail(),则该接口只接受Get请求,如果需要该接口同时支持Post请求,需要在方法名上加上[HttpPost]和[HttpGet]特性
不是Get开头的接口名称,默认支持Get和Post请求,不用添加特性
20、Code first配置数据库主键不自增
this.Property(p => p.ProvinceCode).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
21、配置外键是否级联删除
this.HasRequired(s => s.Area).WithMany().HasForeignKey(s => s.InArea).WillCascadeOnDelete(false);
22、EF Include生成left join或inner join设置
dbRead.Set<Student>().Include(x=>x.ClassRoom);
生成的Sql语句为 inner join
HasRequired(s => s.ClassRoom) .WithMany() .HasForeignKey(student => student.ClassRoomId);
生成的Sql语句为 left join
HasOptional(s => s.ClassRoom) .WithMany() .HasForeignKey(student => student.ClassRoomId);
23、EF相关设置
context.Configuration.LazyLoadingEnabled = false;
context.Configuration.ProxyCreationEnabled = false;
Configuration.AutoDetectChangesEnabled = false;
24、MVC模型验证,支持验证隐藏域的值
<script type="text/javascript">
$.validator.setDefaults({
ignore: [],
});
</script>
25、MVC@Html.添加自定义属性,例子:自定义属性为data-live-search = "true",注意属性的"-"号要换为"_"
@Html.DropDownList("ddlList", new SelectList(ViewBag.List, "Value", "Text"), new { @class = "form-control",@data_live_search = "true" })
26、Autofac注入在异步代码中会出现The request lifetime scope cannot be created because the HttpContext is not available错误解决
1,autofac var resolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = resolver;
2,获取Service ClinicalCaseService = GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(ClinicalCaseService)) as ClinicalCaseService;
参考:https://www.cnblogs.com/icebutterfly/p/7660270.html
27、Asp.net Core异步调用同步方法
AsyncHelper.RunSync(() => _wChatUserAppService.SubscribeAsync(requestMessage.FromUserName, wechatUser.nickname, wechatUser.headimgurl, requestMessage.EventKey, requestMessage.Ticket) );
28、Task.WhenAll 的意思是将所有等待的异步操作同时执行
using (var context = new TestDbContext2()) { var clients = context.Clients.ToListAsync(); var servers = context.Servers.ToListAsync(); await Task.WhenAll(clients, servers); }
29、
30、EF多字段求和(分组/不分组)
分组多字段求和
query.GroupBy(q => new { q.Year, q.Month }) .Select(q => new { Year = q.Key.Year, Month = q.Key.Month, BuildAmount = q.Sum(i => i.BuildAmount), RecAmount = q.Sum(i => i.RecAmount), Amount = q.Sum(i => i.Amount), RealAmount = q.Sum(i => i.RealAmount) });
不分组多字段求和(这样得到的就是对应字段的总的求和,其实还是利用了分组,不过给分组依据传个空,如果利用linq的话就是传个常数)
where.GroupBy(x => new { }).Select(q => new { sumWeight = q.Sum(x => x.Weight), sumQuantity = q.Sum(x => x.Quantity), sumIncome = q.Sum(x => x.Income) }).FirstOrDefault();
31、EF CodeFirst配置一对多关系
Code First配置外键一对多映射
public ICollection<CustomerBillInterestStructure> InterestStructures { get; set; }
Map里面配置this.HasMany(d => d.InterestStructures).WithOptional().HasForeignKey(d => d.BillId);
public Parther Parther { get; set; }
this.HasRequired(r => r.Parther).WithMany().HasForeignKey(r => r.PartherId);
主表
public class Contract:BaseEntity { /// <summary> /// 合同名称 /// </summary> public string CtName { get; set; } /// <summary> /// 模版 /// </summary> public List<ContractTemplate> TemplateList { get; set; } /// <summary> /// 合同模版可用状态 /// </summary> public Status Status { get; set; } } public class ContractMap : EntityTypeConfiguration<Contract> { public ContractMap() { this.ToTable("Contract"); this.HasKey(c => c.Id); this.Property(c => c.CtName).IsRequired().HasMaxLength(100); //定义关系 this.HasMany(c => c.TemplateList).WithOptional().HasForeignKey(d => d.ContractId); } }
子表
/// <summary> /// 合同模版 /// </summary> public class ContractTemplate:BaseEntity { /// <summary> /// 合同ID /// </summary> public int ContractId { get; set; } /// <summary> /// 版本号 /// </summary> public string Version { get; set; } /// <summary> /// 合同文件模版地址 /// </summary> public string TemplateFilePath { get; set; } }