所以我有一个现有的类,看起来像这样:
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
中的每个类。
那我该怎么办呢?是否可以混合使用Fluent API和数据注释?
答案 0 :(得分:0)
尝试从实体调用中删除行.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)
它应该这样工作。也许这post会帮助你。
但是我必须建议你应该避免混合使用Data Annotations和FluentAPI,因为将实体定义拆分成不同的文件会更容易出错!
答案 1 :(得分:0)
好吧,我发现了自己的错误,我感到非常愚蠢: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
。
抛出的异常是关于所有&#34;标准&#34;类,因为它试图根据它们与Song
类的关系将它们加载到模型中(显然,不适合与Entity Framework一起使用的类没有定义键)。