Fluent API One to Many mapping table

别来无恙 提交于 2019-12-25 06:55: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; }
}


来源:https://stackoverflow.com/questions/27185539/fluent-api-one-to-many-mapping-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!