将数据注释与流畅的 API 混合抛出 EntityType 没有为上下文中的每个类定义键



所以我有一个现有的类,看起来像这样:

Public Class Song
    <Key>
    Public Property GUID As Guid
    <ForeignKey("Creator")>
    Public Property GUID_Creator As Guid
    Public Property Creator As User
End Class

这很完美,我可以添加新歌曲等等。

最近,我决定我需要使用 Fluent API 映射一些东西,但我不想使用 API 重新制作我的整个模型,我所需要的只是禁用级联删除。所以我徘徊到onModelCreating,补充

modelBuilder.Entity(Of Song) _
    .HasRequired(Function(s) s.Creator) _
    .WithMany(Function(u) u.Songs) _
    .HasForeignKey(Function(s) s.GUID_Creator) _
    .WillCascadeOnDelete(False)

我补充了一下,该方法之前是空的。在此之后触发应用程序(我启用了自动迁移)并使用上下文时,突然我在我的上下文中得到了每个类的异常,说:

EntityType 'Song' has no key defined
EntityType 'User' has no key defined

等。我在谷歌上搜索了同时使用Fluent API和数据注释的人,发现有些人可以工作。在 Fluent API 中添加HasKey可以解决这个问题,但我不想在 OnModelCreating 中重制每个类。
那么我该怎么做呢?是否可以混合使用流畅的API和数据注释?

尝试从实体调用中删除行.HasKey(Function(s) s.GUID) _,因为您已经通过数据注释定义了它,并且只想设置关系

modelBuilder.Entity(Of Song) _
    .HasRequired(Function(s) s.Creator) _
    .WithMany(Function(u) u.Songs) _
    .HasForeignKey(Function(s) s.GUID_Creator) _
    .WillCascadeOnDelete(False)

它应该以这种方式工作。也许这篇文章会对你有所帮助。

但我必须建议你应该避免混合使用数据注释和FluentAPI,因为将实体定义拆分为不同的文件会更容易出错!

好吧,我发现了我的错误,我觉得自己真的很愚蠢:D

我的项目中有两个类:

Public Class Song 'Class for use in my apps and services
Public Class EF_Song 'Class for use with Entity Framework

所以整个问题是我使用类Song而不是EF_Song。引发的异常是关于所有"标准"类的,因为它试图根据它们与Song类的关系将它们加载到模型中(显然,不用于实体框架的类没有定义键)。

最新更新