让我举两个类的简化示例:
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获取相关记录?
感谢您的关注和时间.
解决方法
如果您不使用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();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。