簡體   English   中英

Entity Framework Core 檢索相關實體

[英]Entity Framework Core retrieving related entities

我是 EFC 的新手,希望能在遇到的問題上得到一些幫助。 假設我有兩張桌子:

工具表:

Version  FeatureId 

1         1

1         2

1         4

2         1

功能表:

FeatureId Name

1         feature1

2         feature2

3         feature3

4         feature4

並基於這兩個表,我有以下內容:

public class Tool
{

public int Id {get; set;}

public int Version { get; set; } 

public List<Feature> Features { get; set; }

}

public class Feature
{

public string FeatureId { get; set; }

public string Name { get; set; }
}

因此,一個工具版本可能包含多個功能,並且一個功能可能包含在多個版本中。 當我嘗試根據版本號檢索工具時,如下所示:

_context.Tool.Where(x => x.Version == versionID)
           .Include(i => i.Features)
           .ToList()

我遇到了一個錯誤,要求提供 ToolId。 這是為什么?

一個工具版本可能包含多個功能,並且一個功能可能包含在多個版本中。

所以你有多對多的關系,你的表必須如下所示:

public class Tool
{
    public int Id {get; set;}
    public int Version { get; set; } 
    public ICollection<Feature> Features { get; set; }
}

public class Feature
{
    public string FeatureId { get; set; }
    public string Name { get; set; }
    public ICollection<Tool> Tools { get; set; }
}

而錯過的一個:

public class ToolsFeatures
{
    public int ToolId { get; set; }
    public Tool Tool { get; set; }

    public int FeatureId { get; set; }
    public Feature Feature { get; set; }
}

然后在 dbcontext 中配置 relashions:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ToolsFeatures>()
        .HasKey(t => new { t.ToolId, t.FeatureId});

        modelBuilder.Entity<ToolsFeatures>()
            .HasOne(t => t.Tool)
            .WithMany(f => f.Features)
            .HasForeignKey(t => t.ToolId);

        modelBuilder.Entity<ToolsFeatures>()
            .HasOne(f => f.Feature)
            .WithMany(t => t.Tools)
            .HasForeignKey(f => f.FeatureId);
    }

查看多對多關系


注意:您將FeatureId定義為string ,但它具有int值? 這里有什么錯誤嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM