我有两个实体,分别代表该Web应用程序的用户和该Web应用程序所涉及的播客中的一个参与者。网页的用户具有个人资料,可以登录,可以发表评论等。参与者与他们出现的情节对象(具有传记,图片等)被链接起来。有可能既是参与者又是用户同时,也可以是用户或参与者。
我正在为EF Core 3.1建模。如果重要的话,我也为此项目使用.Net Core 3.0,并且数据库为Postgresql(使用Nuget包Npgsql.EntityFrameworkCore.PostgreSQL v3.1.0)。
双方的这种关系都应该为可空/不需要。实体非常简单(省略所有非importart属性):
用户:
public class User
{
public Guid UserId { get; set; }
public Participant Participant { get; set; }
public Guid ParticipantId { get; set; }
}
参加者:
public class Participant
{
public Guid ParticipantId { get; set; }
public User User { get; set; }
public Guid UserId { get; set; }
}
我正在尝试使用Fluent API来配置关系-这似乎是它崩溃的地方。
用户配置:
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> user)
{
user.ToTable("users");
user.HasKey(u => u.UserId);
user.HasOne(u => u.Participant)
.WithOne(p => p.User)
.HasForeignKey<Participant>(p => p.UserId);
}
}
参与者配置:
public class ParticipantConfiguration : IEntityTypeConfiguration<Participant>
{
public void Configure(EntityTypeBuilder<Participant> participant)
{
participant.ToTable("participants");
participant.HasKey(p => p.ParticipantId);
participant.HasOne<User>(p => p.User)
.WithOne(u => u.Participant)
.HasForeignKey<User>(u => u.ParticipantId);
}
}
现在,我意识到您应该只配置关系的一侧-至少这就是我解释所读内容的方式。为了完整起见,我仅包括以上内容;我已经尝试过像上面一样一次配置双方,我已经尝试仅在用户端和参与者端进行配置。在每种组合中,代码都会编译,应用程序启动,但是当我尝试通过DbContext将用户实际添加到数据库时,我遇到了相同的异常:
System.InvalidOperationException: 'The child/dependent side could not be determined for the one-to-one relationship between 'Participant.User' and 'User.Participant'. To identify the child/dependent side of the relationship, configure the foreign key property. If these navigations should not be part of the same relationship configure them without specifying the inverse. See http://go.microsoft.com/fwlink/?LinkId=724062 for more details.'
现在,这是彼此完全了解的两个完全独立的对象,因此我不确定孩子/受抚养人的心态是否准确,但是我愿意忽略这一细节而屈服于EF Core的意愿。但是,我无法弄清楚如何让我毫无例外地工作。
TL; DR:
感谢您的任何见解!
我会仔细检查您的配置是否正在被调用。看起来一切正常。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句