C#学习教程:存储库模式仅检索必需的列在代码中,有一个通用的Get方法:publicclassGenericRepositorywhereTEntity:class{internalAdminDbContextcontext;内部DbSetdbSet;publicGenericRepository(AdminDbContextcontext){this.context=context;this.dbSet=context.Set();}publicvirtualIEnumerableGet(Expressionfilter=null,Funcselector=null,FuncorderBy=null,stringincludeProperties=""){IQueryablequery=dbSet;如果(过滤器!=null){query=query.Where(过滤器);}foreach(varincludePropertyinincludeProperties.Split(newchar[]{','},StringSplitOptions.RemoveEmptyEntries)){query=query.Include(includeProperty);}if(orderBy!=null){returnorderBy(query).ToList();}else{returnquery.ToList();}}这个时候调用这个方法,会把数据库中的所有记录都取出来,在内存中进行列选择。我的问题是如何在这里扩展Get方法,这将允许我动态地将列名传递给这个方法,以便在数据库级别只选择所需的列?我尝试了什么:这是一个很长的答案,但这是我为此创建的扩展方法。在这种情况下,我要返回一个对象,因为它在webAPI中用于返回json,我不需要特定类型,但这可以很容易地进行调整以返回通用实体类型。使用系统;使用系统集合;使用System.Collections.Generic;使用System.Linq;使用System.Reflection;使用Newtonsoft.Json.Linq;命名空间Your.Extensions{publicenumPropertyFormat{AsIs,??PascalCase,CamelCase}publicstaticclassDataShapingExtensions{publicstaticobjectToDataShape(thisObjectInobjectToShape,stringfields,PropertyFormatpropertyFormat=PropertyFormat.AsIs)whereObjectIn:class{varlistOfFields=newList();如果(!string.IsNullOrWhiteSpace(fields)){listOfFields=fields.ToLower().Split(',').ToList();}if(listOfFields.Any()){varobjectToReturn=newJObject();//====varenumerable=objectToShapeasIEnumerable;if(enumerable!=null){varlistOfObjects=newList();foreach(variteminenumerable){varobjectToReturn2=newJObject();listOfFields.ForEach(field=>{try{varprop=item.GetType().GetProperty(field,BindingFlags.IgnoreCase|BindingFlags.Public|BindingFlags.Instance);varfieldName=prop.Name;varfieldValue=prop.GetValue(item,null);fieldName=GetName(fieldName,propertyFormat);objectToReturn2.Add(newJProperty(fieldName,fieldValue));}赶上(异常前){}});listOfObjects.Add(objectToReturn2);}返回listOfObjects.ConvertAll(o=>o);}//====listOfFields.ForEach(field=>{try{varprop=objectToShape.GetType().GetProperty(field,BindingFlags.IgnoreCase|BindingFlags.Public|BindingFlags.Instance);varfieldName=prop.Name;varfieldValue=prop.GetValue(objectToShape,null);fieldName=GetName(fieldName,propertyFormat);objectToReturn.Add(newJProperty(fieldName,fieldValue));}catch(Exceptionex){}});返回对象返回;}返回objectToShape;}privatestaticstringGetName(stringfield,PropertyFormatpropertyFormat){switch(propertyFormat){casePropertyFormat.AsIs:returnfield;casePropertyFormat.PascalCase:返回字段.ToPascalCase();案例PropertyFormat.CamelCase:returnfield.ToCamelCase();默认值:返回字段;}}}}//用法[HttpGet,Route("api/someroute")]publicasyncTaskYourMethod(stringfields=null){try{varproducts=awaityourRepo.GetProductsList();如果(fields.HasValue()){返回Ok(products.ToDataShape(fields,PropertyFormat.CamelCase));}返回确定(产品);}catch(Exception){返回InternalServerError();//调用routing/api/someroute?fields=productID,productName//Output(json)以上是C#学习教程:repository模式只检索需要的列分享所有内容,如果对大家有用需要了解更多C#学习教程,希望大家多加关注——{productID:1,productName:"SomeName"}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: