每张图片多个类别(代码优先)

时间:2016-11-11 20:44:36

标签: asp.net-core-mvc entity-framework-core

我试图学习使用Entity Framework核心,但无法使用以下代码。我需要一个具有多个类别的Image的数据库(用于过滤)。

public class ImageCategory
{
    public string CategoryId { get; set; }
    public int ImageId { get; set; }

    //*************
    [ForeignKey("CategoryId")]
    public virtual Category Category { get; set; }
    //*************
    [ForeignKey("ImageId")]
    public virtual Image Image { get; set; }
}

...

public class Category
{
    [Key]
    [Display(Name="Category name")]
    public string Id { get; set; }
}

.....

public class Image
{
    [Key]
    public int Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }

    [FileExtensions(Extensions = "jpg,png,gif,jpeg,bmp,svg")]
    [DataType(DataType.ImageUrl)]
    public string ThumbnailUrl { get; set; }

    [Required]
    [FileExtensions(Extensions = "jpg,png,gif,jpeg,bmp,svg")]
    [DataType(DataType.ImageUrl)]
    public string ImageUrl { get; set; }

    [FileExtensions(Extensions = "jpg,png,gif,jpeg,bmp,svg")]
    [DataType(DataType.ImageUrl)]
    public string ImageUrlFullRes { get; set; }

    [Required]
    public string AltText { get; set; }

    public int NumberOfViews { get; set; }

    [Required]
    [DataType(DataType.Date)]
    public DateTime UploadDate { get; set; }

    //*************
    [Required]
    public virtual ICollection<ImageCategory> Categories { get; set; }
}

Add-Migrations生成以下文本:

    PM> Add-Migration InitialMigration -context ImageContext
System.InvalidOperationException: The entity type
'quandar_eu.Models.Images.ImageCategory' requires a primary key to be defined.

如果您只想加入2个表,那么您不需要主键吗?我试图谷歌解决方案,但找不到它。

良好教程/电子书的链接有很大帮助,因为我想学到更多东西。

修改 感谢Ivan Stoev。这是让它全部工作的最后一段代码。

public class ImageContext : DbContext
{
    public ImageContext(DbContextOptions<ImageContext> options) : base(options)
    {

    }

    public DbSet<Image> Image { get; set; }

    public DbSet<Category> Category { get; set; }

    public DbSet<ImageCategory> ImageCategory { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ImageCategory>().HasKey(e => new { e.CategoryId, e.ImageId });
    }
}

1 个答案:

答案 0 :(得分:0)

您需要为ImageCategory配置复合 PK(主键)。目前只能使用Fluent API(参考:EF Core: Keys (primary))。

DbContext派生类中,覆盖OnModelCreating(如果您还没有)并添加以下内容:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ImageCategory>().HasKey(e => new { e.CategoryId, e.ImageId });
    // ...
}