不幸的是,似乎没有办法以我想要的方式映射 ID。但是,这里有三种解决方法,说明如何实现所需实体键的检索。
Ben Reich 提出的第一个解决方案。
实现 get-only 属性,它将仅返回链接实体的 ID。
public class Company
{
public virtual ICollection<Article> Articles { get; set; }
public IEnumerable<int> ArticlesIds
{
get { return Articles.Select(a => a.Id); }
}
}
使用起来似乎很方便,但是,它有一个缺点 - 将从数据库中读取整个实体以接收唯一的 ID。这是来自 SQL Profiler 的此类调用的日志:
exec sp_executesql N'SELECT
[Extent2].[Id] AS [Id],
[Extent2].[Header] AS [Header],
[Extent2].[Description] AS [Description],
[Extent2].[Text] AS [Text],
[Extent2].[CreationDate] AS [CreationDate],
[Extent2].[AccountId] AS [AccountId],
[Extent2].[ImageSetId] AS [ImageSetId]
FROM [dbo].[CompanyArticles] AS [Extent1]
INNER JOIN [dbo].[Articles] AS [Extent2] ON [Extent1].[Article_Id] = [Extent2].[Id]
WHERE [Extent1].[Company_Id] = @EntityKeyValue1',N'@EntityKeyValue1 int',@EntityKeyValue1=1
第二种解决方案。
使用相同的模型,读取实体后分别读取ID。
var ids = db.Set<Article>().Where(a => a.Companies.Select(c => c.Id).Contains(f.Id)).ToList();
这种方法与前一种方法完全相同,将获取整个实体集。
exec sp_executesql N'SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Header] AS [Header],
[Extent1].[Description] AS [Description],
[Extent1].[Text] AS [Text],
[Extent1].[CreationDate] AS [CreationDate],
[Extent1].[AccountId] AS [AccountId],
[Extent1].[ImageSetId] AS [ImageSetId]
FROM [dbo].[Articles] AS [Extent1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[ArticleCompanies] AS [Extent2]
WHERE ([Extent1].[Id] = [Extent2].[Article_Id]) AND ([Extent2].[Company_Id] = @p__linq__0)
)',N'@p__linq__0 int',@p__linq__0=1
第三种解决方案。从我的角度来看,最合适的。
为中间表创建实体类。
public class ArticleCompany
{
public int CompanyId { get; set; }
public int ArticleId { get; set; }
public virtual Company Company { get; set; }
public virtual Article Article { get; set; }
}
将两个实体与该实体映射为 1 对 m 关系。不要忘记映射新实体本身。
modelBuilder.Entity<Article>().HasMany(a => a.ArticlesCompanies).WithRequired(ac => ac.Article).HasForeignKey(ac => ac.ArticleId);
modelBuilder.Entity<Company>().HasMany(c => c.ArticlesCompanies).WithRequired(ac => ac.Company).HasForeignKey(ac => ac.CompanyId);
modelBuilder.Entity<ArticleCompany>().ToTable("ArticlesCompanies");
modelBuilder.Entity<ArticleCompany>().HasKey(ac => new { ac.ArticleId, ac.CompanyId });
然后,在获取实体后,使用中间表来获取相关 ID:
var ids = db.Set<ArticleCompany>().Where(ca => ca.CompanyId == companyEntity.Id).Select(ca => ca.ArticleId);
对应的 SQL 日志(仅从数据库中获取 ID):
exec sp_executesql N'SELECT
[Extent1].[ArticleId] AS [ArticleId]
FROM [dbo].[ArticlesCompanies] AS [Extent1]
WHERE [Extent1].[CompanyId] = @p__linq__0',N'@p__linq__0 int',@p__linq__0=1