0

如果有人可以向我解释如何使用 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; } 
}
4

1 回答 1

0

添加新表:

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; }
}
于 2014-11-28T09:38:41.017 回答