如何设置与此查询的区别
return _dataContext.ProjectPictures.Include("Projects").Include("ProjectPictureTypes").Where(p => p.ProjectPictureTypes.Id == 1).ToList();
我需要像
这样的东西return _dataContext.ProjectPictures.Include("Projects").Include("ProjectPictureTypes").Where(p => p.ProjectPictureTypes.Id == 1).Distinct(p=>p.Projects.Id).ToList();
答案 0 :(得分:1)
假设您在数据库中按照您希望的方式设置了外键关系,并假设您的LINQ-to-SQL类完全反映了这些关系,看起来您想要的东西如下:
DataContext.Projects
.Where(a => a.ProjectPictures.ProjectPictureType_ID == 1)
.Distinct()
.Select(a => a.Project_ID)
.ToList()
我假设您的数据库结构如下所示:
Projects ProjectPictures
======== ===============
Project_ID (PK, int) ProjectPicture_ID (PK, int)
Project_ID (FK, int)
ProjectPictureType_ID (FK, int)
ProjectPictureTypes
===================
ProjectPictureType_ID (PK, int)
答案 1 :(得分:0)
据我所知,您希望所有与“ProjectPictureTypes”链接的项目ID为1。
据我所知,你可能想看看分组和合适的聚合 - 不管这是什么。然后p.Projects.Id上的分组对于p.Projects.Id是不同的。困难时期可能是适当的聚合 - 如果在商业逻辑意义上有一个。
HTH
答案 2 :(得分:0)
您必须编写自定义IEqualityComparer
public class ProjectPicturesComparer: IEqualityComparer< ProjectPictures >
{
// Products are equal if their names and product numbers are equal.
public bool Equals(ProjectPictures p, ProjectPictures p2)
{
return p.Projects.Id == p2.Projects.Id;
}
// If Equals() returns true for a pair of objects,
// GetHashCode must return the same value for these objects.
public int GetHashCode(ProjectPictures p)
{
// Calculate the hash code for the product.
return p.Projects.Id.GetHashCode();
}
}
然后你会做
return _dataContext.ProjectPictures.Include("Projects").Include("ProjectPictureTypes").Where(p => p.ProjectPictureTypes.Id == 1)..Distinct(new ProjectPicturesComparer()).ToList()