Проблема с отображением Entity Framework 2.1 - PullRequest
0 голосов
/ 18 сентября 2018

Я обновил плагин с .NET Framework 4.6.1 до .NET Core 2.1 и у меня возникли проблемы с отображением EF.

У меня есть класс в 4.6.1, который расширяет базовый класс Picture:

public partial class PictureExt : Picture
{
    public virtual string ExternalUrl { get; set; }
}

базовый класс:

public partial class Picture : BaseEntity
{
    public string MimeType { get; set; }
    public string SeoFilename { get; set; }
    public string AltAttribute { get; set; }
    public string TitleAttribute { get; set; }
    public bool IsNew { get; set; }
    public virtual PictureBinary PictureBinary { get; set; }
}

и в 4.6.1 я сделал отображение:

    public PictureMap()
    {
        this.ToTable("Picture");
        this.HasKey(p => p.Id);
        this.Property(p => p.PictureBinary).IsMaxLength();
        this.Property(p => p.MimeType).IsRequired().HasMaxLength(40);
        this.Property(p => p.SeoFilename).HasMaxLength(300);
        this.Property(p => p.ExternalUrl).IsOptional();
    }

и все отлично работает

, но в .NET Core EFЯ сделал отображение:

    public override void Configure(EntityTypeBuilder<PictureExt> builder)
    {
        builder.ToTable("Picture");
        builder.HasKey(picture => picture.Id);
        builder.Property(picture => 
        picture.MimeType).HasMaxLength(40).IsRequired();
        builder.Property(picture => picture.SeoFilename).HasMaxLength(300);
        builder.Property(p => p.ExternalUrl);
        base.Configure(builder);
    }

, и у меня есть исключение:

A key cannot be configured on 'PictureExt' because it is a derived type. The key must be configured on the root type 'Picture'. If you did not intend for 'Picture' to be included in the model, ensure that it is not included in a DbSet property on your context, referenced in a configuration call to ModelBuilder, or referenced from a navigation property on a type that is included in the model

Я понимаю, что я сделал неправильно, но я не знаю, как это сделать правильно,Может как то так?https://stackify.com/new-in-net-core-2-1/#post-19576-_kaymrlea07yf

Но как это реализовать?

1 Ответ

0 голосов
/ 18 сентября 2018

Что вы можете сделать, это убедиться, что у вас нет DbSet<Picture> или DbSet<BaseEntity> на вашем DbContext. Если приведенное ниже решение не подходит для вашей ситуации, обновите ваш вопрос, чтобы мы могли соответствующим образом обновить наши ответы. :)

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using System;
using Xunit;

public class Tests
{
    [Fact]
    public void Can_add_PictureExt()
    {
        var options = new DbContextOptionsBuilder<Context>()
            .UseInMemoryDatabase(Guid.NewGuid().ToString())
            .Options;

        using (var ctx = new Context(options))
        {
            ctx.Add(new PictureExt());
            ctx.SaveChanges();
        }

        using (var ctx = new Context(options))
        {
            Assert.Single(ctx.PictureExt);
        }
    }
}
public class Context : DbContext
{
    public Context(DbContextOptions<Context> options) : base(options) { }

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

    //uncommenting any of the following DbSet will throw exception

    //public DbSet<Picture> Picture { get; set; }

    //public DbSet<BaseEntity> BaseEntity { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration(new PictureExtConfiguration());
    }
}
public class PictureExtConfiguration : IEntityTypeConfiguration<PictureExt>
{
    public void Configure(EntityTypeBuilder<PictureExt> builder)
    {
        builder.ToTable("Picture");
        builder.HasKey(picture => picture.Id);
        builder.Property(picture =>
        picture.MimeType).HasMaxLength(40).IsRequired();
        builder.Property(picture => picture.SeoFilename).HasMaxLength(300);
        builder.Property(p => p.ExternalUrl);

        //commented out to simplify example
        //base.Configure(builder);
    }
}
public partial class PictureExt : Picture
{
    public virtual string ExternalUrl { get; set; }
}
public partial class Picture : BaseEntity
{
    public string MimeType { get; set; }
    public string SeoFilename { get; set; }
    public string AltAttribute { get; set; }
    public string TitleAttribute { get; set; }
    public bool IsNew { get; set; }

    //commented out to simplify example
    //public virtual PictureBinary PictureBinary { get; set; }
}
public class BaseEntity
{
    public int Id { get; set; }
}
...