c# – 如何让Automapper通过Id字段上的内连接获取相关记录,而不
我一直在使用Automapper一段时间了,到目前为止它一切都很棒.但最近我遇到了一些“限制”(或缺乏我的知识).
让我举两个类的简化示例: public class Consumable { public int ConsumableId { get; set; } public string Description { get; set; } public int SaleDepartmentId { get; set; } } public class SaleDepartment { public int SaleDepartmentId { get; set; } public string Description { get; set; } } 这两个实体存储了SaleDepartment的Id,但是没有将SaleDepartment链接到Consumable的外键(我不希望它作为键),但SaleDepartment在SaleDepartmentId上有PrimaryKey 现在我的DTO看起来非常相似 public class ConsumableDTO { public int ConsumableId { get; set; } public string Description { get; set; } public int SaleDepartmentId { get; set; } } 这是映射 Mapper.CreateMap<Consumable,ConsumableDTO>().ReverseMap(); 因此,每当我带来一个消耗品DTO集合时,我也想带上相关的SaleDepartment的描述, Mapper.Map<ObservableCollection<Consumable>> (context.Consumable.Project().To<ConsumableDTO>()); 但是因为这样的密钥不存在,我如何告诉自动化程序根据我拥有的这些ID进行内连接? 这就是我获得相关记录的方式 var foo = new ObservableCollection<Consumable>( (from c in context.Consumable.Project().To<ConsumableDTO>() join sd in context.SaleDepartment on c.SaleDepartmentId equals sd.SaleDepartmentId select new { consumable = c,SaleDepartmentDescription = sd.Description }).ToList() .Select(p => Mapper.Map<ConsumableDTO,Consumable>(p.consumable,new Consumable() { SaleDepartmentDescription = p.SaleDepartmentDescription }))); 所以,这将抓取或消费,然后内部加入saledeparments并选择内部联接的描述形式,但似乎很少的步骤,是否有一种更简单的方式来告诉自动播放器,根据这个匹配的ID获取相关记录? 感谢您的关注和时间. 解决方法
首先,我假设你的DTO意在包含公共字符串SaleDepartmentDescription {get;组;如你的问题引用它但它实际上并不存在.
如果您不使用EF迁移(这是一个公平的假设,否则您只需添加外键!),那么您可以通过在实体中添加密钥来实现这一点 – 实际上不需要在数据库中为密钥提供密钥加入他们,这只是告诉EF假装他们是. (如果您正在使用EF迁移,则此方法将不起作用,因为它将要将密钥添加到数据库.) public class Consumable { public int ConsumableId { get; set; } public string Description { get; set; } public int SaleDepartmentId { get; set; } [ForeignKey("SaleDepartmentId")] public virtual SaleDepartment SaleDepartment { get; set; } } 假设您的DTO确实包含字符串属性SaleDepartmentDescription,那么AutoMapper将自动处理此问题,但您应该使用ProjectTo来进行更有效的数据库查询: var mappedDTOs = context.Consumable.ProjectTo<ConsumableDTO>().ToList(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |