简体   繁体   中英

Entity Framework Core retrieving related entities

I'm new to EFC and was hoping to get some help with a problem I ran into. Suppose I have two tables:

Tool table:

Version  FeatureId 

1         1

1         2

1         4

2         1

Feature Table:

FeatureId Name

1         feature1

2         feature2

3         feature3

4         feature4

and based on these two tables I have the following:

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

so a tool version may include more than one features and a feature may be included in more than one version. When I tried to retrieve a tool based on the version number like this:

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

I ran into an error asking for a ToolId. Why is that?

a tool version may include more than one features and a feature may be included in more than one version.

So you have many-to-many relashionship, and your tables must look like below:

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

And the missed one:

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

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

Then configure the relashions the dbcontext:

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

See Many-to-Many relashions


Notice: You have FeatureId defined as string but it has int values? is there any mistake here?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM