[英]EF core many to many configuration not working with Fluent API
我在使用 Fluent API 和 EF Core 理解和實現多對多關系時遇到了麻煩。
我已經查看了這個問題,並完全按照此方式建立了我的關系,但出現以下錯誤:
錯誤 CS1061“CollectionNavigationBuilder”不包含“WithMany”的定義,並且找不到接受“CollectionNavigationBuilder”類型的第一個參數的擴展方法“WithMany”(您是否缺少 using 指令或程序集引用?)
這是我的意圖。 我有一個客戶,他有很多工作。 我應該能夠獲得與該客戶相關的所有工作。 EF 應該在后台創建連接表...
這是我的課程:
public class Client : IEntityBase
{
public int Id { get; set; }
public int? JobId { get; set; }
public ICollection<Job> Jobs { get; set; }
}
public class Job : IEntityBase
{
public int Id { get; set; }
}
//my interface
public interface IEntityBase
{
int Id { get; set; }
}
編輯這是我嘗試過的 Fluent API 以及在“.withMany”上出現錯誤的地方
modelBuilder.Entity<Client>()
.HasMany(p => p.Jobs)
.WithMany(p => p.clients)
.Map(m =>
{
m.MapLeftKey("ClientId");
m.MapRightKey("JobId");
m.ToTable("ClientJob");
});
根據 Chris Sakell 的博客,我正在使用通用存儲庫模式。 這是檢索客戶端的代碼:
IEnumerable<Client> _clients = _clientRepository
.AllIncluding(s => s.Creator, s => s.Jobs, s => s.State)
.OrderBy(s => s.Id)
.Skip((currentPage - 1) * currentPageSize)
.Take(currentPageSize)
.ToList();
我正在使用通用代碼:
public virtual IEnumerable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = _context.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query.AsEnumerable();
}
我如何配置它以便我可以根據上面的 Allinclude 語句使用 include 屬性檢索作業?
您嘗試實現的 Fluent API 示例來自 EF 6。多對多關系配置在 EF Core 中略有不同。 首先,您需要包含一個實體來表示連接/橋接表:
public class ClientsJobs
{
public int ClientId { get; set; }
public int JobId { get; set; }
public Client Client { get; set; }
public Job Job { get; set; }
}
然后在 OnModelCreating 方法中像這樣配置它:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ClientsJobs>()
.HasKey(x => new { x.ClientId, x.JobId });
modelBuilder.Entity<ClientsJobs>()
.HasOne(x => x.Client)
.WithMany(y => y.Jobs)
.HasForeignKey(y => y.JobId);
modelBuilder.Entity<ClientsJobs>()
.HasOne(x => x.Job)
.WithMany(y => y.Clients)
.HasForeignKey(y => y.ClientId);
}
在此處查看更多信息: http : //www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration
注意:您確實需要在相關類中包含關系兩端的導航屬性,因此您需要將Clients
屬性添加到您的Job
實體。
對於 EF Core 5.0 及更高版本,您可以(最后)對多對多使用直接關系:
modelBuilder
.Entity<Post>()
.HasMany(p => p.Tags)
.WithMany(p => p.Posts)
.UsingEntity(j => j.ToTable("PostTags"));
資料來源: 關系 - EF Core | 微軟(多對多)
您也應該將 Clients 屬性添加到 Job 類:
public class Job : IEntityBase
{
public int Id { get; set; }
public ICollection<Client> Clients{ get; set; }
}
那么一切都應該井然有序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.