简体   繁体   English

将dto映射到实体? 也许自动映射? 属性应该匹配吗? LINQ选择

[英]mapping dto to entities? maybe automapper? should properties match? linq selection

I am trying to create a LINQ-to-SQL solution using what I will call basic linq-to-sql. 我正在尝试使用所谓的基本linq-to-sql创建LINQ-to-SQL解决方案。 It is not a full ORM solution via EF or anything like that. 它不是通过EF之类的完整的ORM解决方案。 The point right now is to leverage the power of LINQ and reduce stored procedures (as well as some other benefits). 现在的重点是利用LINQ的功能并减少存储过程(以及其他一些好处)。

I have done some work with DTOs and entities before... but that too was a custom implementation. 之前,我已经与DTO和实体进行过一些合作……但这也是一个自定义实现。 In that implementation automapper was used. 在该实现中,使用了自动映射器。 I know automapper "works best" when entitiy properties match DTO properties. 我知道当实体属性与DTO属性匹配时,自动映射器“效果最佳”。 But what if they don't? 但是,如果他们不这样做怎么办? Can you configure it in a custom way? 您可以自定义方式配置它吗?

I suppose a bigger question is... is this a real solution for the fact that you cannot instantiate "LINQ-mapped" "entities" in a query. 我想一个更大的问题是……这是否是无法在查询中实例化“ LINQ映射”“实体”这一事实的真正解决方案? To be clear you cannot use linq and select a new "entity" you would have to select an unmapped DTO. 为了清楚起见,您不能使用linq并选择一个新的“实体”,您必须选择一个未映射的DTO。 What I am ultimately trying to do is avoid "mapping" the entity to the DTO in a given query. 我最终想要做的是避免在给定查询中将实体“映射”到DTO。 I suppose this is not that big of a deal but does something like automapper solve this problem? 我想这没什么大不了的,但是像automapper这样的东西可以解决这个问题吗?

I'm not exactly sure what you're asking but: 我不确定您要问什么,但:

I know automapper "works best" when entitiy properties match DTO properties. 我知道当实体属性与DTO属性匹配时,自动映射器“效果最佳”。 But what if they don't? 但是,如果他们不这样做怎么办? Can you configure it in a custom way? 您可以自定义方式配置它吗?

If you're asking what I think you're asking you should look into .ForMember and overriding the Convert function. 如果您问的是我的想法,那么您应该研究.ForMember并重写Convert函数。 There are examples of both on the wiki: .ForMember: https://github.com/AutoMapper/AutoMapper/wiki/Projection Convert: https://github.com/AutoMapper/AutoMapper/wiki/Custom-type-converters 在Wiki上都有这两种示例:.ForMember: https : //github.com/AutoMapper/AutoMapper/wiki/Projection转换: https : //github.com/AutoMapper/AutoMapper/wiki/Custom-type-converters

Automapper does work "best" when dtos and entities match up because it's super easy to set up a map between the two is their property names and types match. 当dto和实体匹配时,Automapper的确是“最佳”工作,因为在两者之间设置映射非常容易,因为它们的属性名称和类型匹配。 When they don't match you need to manually select properties with .ForMember or manually do the whole conversion by overriding the Convert function. 当它们不匹配时,您需要使用.ForMember手动选择属性,或者通过重写Convert函数手动进行整个转换。

I hope this is a little helpful. 我希望这会有所帮助。 Pop a comment below if it wasn't or you need more info. 如果不是,或者您需要更多信息,请在下面弹出评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM