如何简便创建含已有类全部属性及额外字段的匿名类型?
嘿,这个问题我太有共鸣了!每次写LINQ的Select都要把POCO的所有属性列一遍,再加个UUID,真的挺繁琐的。给你几个更简洁的实现思路,不管用C#还是VB都能搞定:
方案1:直接扩展POCO类(最省事的选择,如果你能修改原类)
如果你的Person类是可以修改的,直接给它加一个Uuid属性就一劳永逸了——这样返回的时候直接用Person对象列表就行,不用额外创建匿名类型:
C# 示例
public class Person { public string Name { get; set; } public int Age { get; set; } // 新增UUID属性 public Guid Uuid { get; set; } } // 查询时直接赋值UUID var people = _dbContext.People .Select(p => new Person { Name = p.Name, Age = p.Age, Uuid = Guid.NewGuid() }) .ToList();
VB 示例
Public Class Person Public Property Name As String Public Property Age As Integer ' 新增UUID属性 Public Property Uuid As Guid End Class ' 查询时赋值UUID Dim people = _dbContext.People _ .Select(Function(p) New Person With { .Name = p.Name, .Age = p.Age, .Uuid = Guid.NewGuid() }) _ .ToList()
方案2:用AutoMapper做映射(适合不能修改原POCO的场景)
如果原Person类是不能动的(比如来自第三方库),用AutoMapper可以避免重复写Select的冗余代码。只需要配置一次映射规则,之后就能一键转换:
C# 示例
先安装AutoMapper NuGet包,然后定义DTO和映射:
// 定义带UUID的DTO类 public class PersonWithUuid { public string Name { get; set; } public int Age { get; set; } public Guid Uuid { get; set; } } // 配置映射规则:把Person的属性映射到PersonWithUuid,同时生成UUID var config = new MapperConfiguration(cfg => { cfg.CreateMap<Person, PersonWithUuid>() .ForMember(dest => dest.Uuid, opt => opt.MapFrom(_ => Guid.NewGuid())); }); IMapper mapper = config.CreateMapper(); // 查询时直接映射,不用手动写每个属性 var people = _dbContext.People .ProjectTo<PersonWithUuid>(mapper.ConfigurationProvider) .ToList();
VB 示例
' 定义带UUID的DTO类 Public Class PersonWithUuid Public Property Name As String Public Property Age As Integer Public Property Uuid As Guid End Class ' 配置映射规则 Dim config = New MapperConfiguration(Sub(cfg) cfg.CreateMap(Of Person, PersonWithUuid)() _ .ForMember(Function(dest) dest.Uuid, Sub(opt) opt.MapFrom(Function(_) Guid.NewGuid())) End Sub) Dim mapper As IMapper = config.CreateMapper() ' 查询时一键映射 Dim people = _dbContext.People _ .ProjectTo(Of PersonWithUuid)(mapper.ConfigurationProvider) _ .ToList()
方案3:序列化时动态添加字段(无需定义新类)
如果不想额外定义DTO类,也可以在JSON序列化阶段动态插入UUID字段,比如用Newtonsoft.Json的JObject来处理:
C# 示例
using Newtonsoft.Json.Linq; // 先获取原Person对象,再给每个对象动态添加UUID字段 var people = _dbContext.People .Select(p => new { Person = p, Uuid = Guid.NewGuid() }) .Select(item => { var jObj = JObject.FromObject(item.Person); jObj.Add("Uuid", item.Uuid); return jObj; }) .ToList(); // 直接序列化这个JObject列表即可 string json = Newtonsoft.Json.JsonConvert.SerializeObject(people);
VB 示例
Imports Newtonsoft.Json.Linq ' 动态添加UUID字段 Dim people = _dbContext.People _ .Select(Function(p) New With {.Person = p, .Uuid = Guid.NewGuid()}) _ .Select(Function(item) Dim jObj = JObject.FromObject(item.Person) jObj.Add("Uuid", item.Uuid) Return jObj End Function) _ .ToList() ' 序列化 Dim json = Newtonsoft.Json.JsonConvert.SerializeObject(people)
内容的提问来源于stack exchange,提问作者ryan
相关产品推荐
相关产品推荐

