【发布时间】:2018-09-17 22:41:58
【问题描述】:
我将一个插件从 .NET Framework 4.6.1 升级到 .NET Core 2.1,但遇到 EF 映射问题。
我有 4.6.1 中的类扩展基本图片类:
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
但是如何实现呢?
【问题讨论】:
-
net461 到 netcore21 不是必需的,重要的是看起来您正在从 EF6 升级到 EF Core。并且两者之间有很多不同之处。无论如何,我注意到在 EF6 中配置
Picture类,而在 EF Core 中配置PictureEx类,这是为什么呢? -
@IvanStoev 您的问题的答案我发现隐藏在 GitHub 问题中,但不确定它的含义! =P "必须在基本类型上定义键,因为 EF 允许将派生实体分配给使用基本实体类型配置的导航。如果您不需要跟踪基本实体类型,您可以在 'OnModelCreating' 中忽略它" @ 987654322@
-
这里是解释如何使用 EF Core 处理关系数据库的文档。在更新我的答案之前,我需要实际阅读此内容。 docs.microsoft.com/en-us/ef/core/modeling/relational/…
标签: entity-framework asp.net-core-mvc nopcommerce