gpt4 book ai didi

c# - EF 核心多对多配置不适用于 Fluent API

转载 作者:太空狗 更新时间:2023-10-30 00:30:04 24 4
gpt4 key购买 nike

我在使用 FLuent API 和 EF Core 理解和实现多对多重复关系时遇到了问题。

我看过this问题并完全建立我的关系,但我收到以下错误:

Error CS1061 'CollectionNavigationBuilder' does not contain a definition for 'WithMany' and no extension method 'WithMany' accepting a first argument of type 'CollectionNavigationBuilder' could be found (are you missing a using directive or an assembly reference?)

这是我的意图。我有一个客户有很多工作。我应该能够获得与该客户相关联的所有工作。 EF 应该在后台创建连接表...

这是我的类(class):

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();
}

如何配置它以便我可以根据上面的 Allincluding 语句使用 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 属性添加到您的工作实体。

关于c# - EF 核心多对多配置不适用于 Fluent API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42337911/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com