Fluent API One to Many mapping table

2019-09-07 09:39发布

问题:

It's really helpful if anyone could explain me how to create a mapping (associated)table for one to many relationship using Fluent API.`

    public class Category
{
public int ID { get; set; }
public string Name { get; set; }
public List<Image> Images { get; set; } 
}

public class Image
{
public int ID { get; set; }
public string Name { get; set; }
public List<Category> Category{ get; set; } 

The mapping table should contain CategoryID and ImageID. The solution should be something similar to this. (This is for many to many)

        modelBuilder.Entity<Category>()
            .HasMany(c => c.Images).WithMany(i => i.Categories)
            .Map(t => t.MapLeftKey("CategoryID")
                .MapRightKey("ImageID")
                .ToTable("CategoryImage"));

I want Fluent API to create new mapping table for the below relationship.

 public class Category
{
public List<Image> Images{get; set;}
}

public class Image
{

public Category Category{ get; set; } 
}

回答1:

Adding NewTable:

modelBuilder
    .Entity<NewTable>()
    .HasRequired(_ => _.Category)
    .WithMany()
    .HasForeignKey(_ => _.CategoryId);

modelBuilder
    .Entity<Image>()
    .HasRequired(_ => _.NewTable)
    .WithMany(_ => _.Images)
    .HasForeignKey(_ => _.NewTableId)

public class NewTable
{
    public int ID { get; set; }
    public int CategoryId { get; set; }
    public List<Image> Images { get; set; }
    public virtual Category Category { get; set; } 
}

public class Image
{
    public int ID { get; set; }
    public string Name { get; set; }
    public List<Category> Categories { get; set; }
    public int NewTableId { get; set; } 
    public virtual NewTable NewTable { get; set; }
}