本文介绍了实体框架在加入后返回不同的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 考虑到我们有这两个实体和一个自定义对象: public class Entiy1 { public int Id {get;组; } public int DestinationId {get;组; } public string Name {get;组; } public string JobTitle {get;组; } } public class Entiy2 { [Key] public int DestinationId {get;组; } public int DestinationName {get;组; } } public class EntityDTO { public int DestinationName {get;组; } public int DestinationId {get;组; } public string Name {get;组; } public string JobTitle {get;组; } 数据是这样的:如何选择不同的destinationId,然后从Entity1中选择Name和JobTitle,然后将它们与Entity2获取目标名称并将其作为EntityDTO返回? 解决方案这是一种方法: var query = from e1 in (从e1 in entities1 group e1 by e1.DestinationId into grp select grp.First()) join e2在e2上的entities2中.DestinationId等于e2.DestinationId 选择新的EntityDTO { DestinationId = e1.DestinationId, DestinationName = e2.DestinationName, Name = e1。名称, JobTitle = e1.JobTitle }; 诀窍是的组,然后采取分组的第一个要素。像 MoreLinq 这样的图书馆也提供开箱即用的独特之处 。 Consider we have these two entities and one custom object : public class Entiy1{ public int Id { get; set; } public int DestinationId { get; set; } public string Name { get; set; } public string JobTitle { get; set; }}public class Entiy2{ [Key] public int DestinationId { get; set; } public int DestinationName { get; set; }}public class EntityDTO{ public int DestinationName { get; set; } public int DestinationId { get; set; } public string Name { get; set; } public string JobTitle { get; set; }}Data is something like this :How can I select distinct destinationId and select Name and JobTitle from Entity1 then join them with Entity2 to fetch destination name and returning them as EntityDTO ? 解决方案 Here's a way to do it:var query = from e1 in (from e1 in entities1 group e1 by e1.DestinationId into grp select grp.First()) join e2 in entities2 on e1.DestinationId equals e2.DestinationId select new EntityDTO { DestinationId = e1.DestinationId, DestinationName = e2.DestinationName, Name = e1.Name, JobTitle = e1.JobTitle } ;The trick is the group by and then taking the first element of the grouping. This is also referred to as "distinct by" that a library like MoreLinq provides out of the box. 这篇关于实体框架在加入后返回不同的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-29 17:35