Fluent API一对多映射表

时间:2014-11-28 09:29:11

标签: asp.net-mvc entity-framework ef-fluent-api

如果有人能解释如何使用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; } 

映射表应包含CategoryID和ImageID。 解决方案应该与此类似。 (这是为了许多人)

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

我希望Fluent API为以下关系创建新的映射表。

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

public class Image
{

public Category Category{ get; set; } 
}

1 个答案:

答案 0 :(得分:0)

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