【发布时间】:2021-05-30 08:01:11
【问题描述】:
我使用实体框架核心 5.0,并使用 fluent api 创建了我的一对多关系。
当我尝试在我的项目中创建一个新用户时,我得到了这个错误。
让我带你去我的User 班级:
public class User : Base
{
[Key]
public int UserID { get; set; }
public string UserName { get; set; }
public string UserSurname { get; set; }
public string UserPassword { get; set; }
public string UserEMail { get; set; }
public int? AgencyID { get; set; }
public virtual Agency Agency { get; set; }
}
public class UserConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(user => user.UserID);
}
}
这里是一个与User 类相关的Agency 类:
public class Agency : Base
{
[Key]
public int AgencyID { get; set; }
public string AgencyName { get; set; }
public string AgencyPhoto { get; set; }
public string AgencyEMail { get; set; }
public string AgencyPhone { get; set; }
public int AgencyExportArea { get; set; }
public virtual ICollection<User> Users { get; set; }
}
public class AgencyConfiguration : IEntityTypeConfiguration<Agency>
{
public void Configure(EntityTypeBuilder<Agency> builder)
{
builder.HasKey(agency => agency.AgencyID);
builder.HasMany(us => us.Users)
.WithOne(us => us.Agency)
.HasForeignKey(au => au.UserID)
.IsRequired(false)
}
}
我知道,我收到了那个错误SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Users_Agencies_UserID". The conflict occurred in database "anan", table "dbo.Agencies", column 'AgencyID'.,因为Agency 表中没有数据。我试图做的事情是使 AgencyID 外键可选作为可空值。在User 类中,您可以看到我将 AgencyID 定义为可为空的。
我真的需要将这种关系定义为一对一或零,还是有其他方法可以做到这一点?
如果我必须将这种关系定义为一对一或零,你能告诉我如何做到这一点吗?
【问题讨论】:
-
您使用的是什么版本的 EF 内核?
-
我使用实体框架核心5.0
标签: c# .net-core entity-framework-core ef-code-first ef-core-5.0