2017-02-20 36 views
0

我无法理解并使用FLuent API和EF Core来实现多对多的repationship。EF核心多对多配置不适用于Fluent API

我已经看过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应在后台创建连接表...

这里是我的课:

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

编辑这里是流利的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(); 
    } 

我怎么配置这个,所以我可以使用includeproperty为每以及检索作业上面的Allincluding声明?

+0

查看EF Core文档 - [Relationships](https://docs.microsoft.com/en-us/ef/core/modeling/relationships) - **多对多** –

回答

0

您应该将客户属性添加到作业类太:

public class Job : IEntityBase 
{ 
    public int Id { get; set; } 
    public ICollection<Client> Clients{ get; set; } 
} 

然后一切都应该是为了。

+0

仍然获得错误“CollectionNavigationBuilder 不包含”withMany“的定义,即使我添加了此... – si2030

0

您尝试实施的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实体。