[英]Entity Framework validation error when nullable FK is null
Info: .Net Framework WPF application, Entity Framework 6信息:.Net Framework WPF 应用程序,实体框架 6
When I try to add an entity to my database table with its nullable foreign key set to null, I get the following validation error from Entity Framework:当我尝试将实体添加到我的数据库表中并将其可为空的外键设置为 null 时,我从 Entity Framework 收到以下验证错误:
Exception thrown: 'System.Data.Entity.Validation.DbEntityValidationException' in EntityFramework.dll抛出异常:EntityFramework.dll 中的“System.Data.Entity.Validation.DbEntityValidationException”
Entity of type "Item" in state "Added" has the following validation errors: state“已添加”中“项目”类型的实体具有以下验证错误:
Property: "SomeForeignKeyId",属性:“SomeForeignKeyId”,
Error: "Field "SomeForeignKeyID" is required.错误:“字段“SomeForeignKeyID”是必需的。
I have the foreign key declared without any attributes such as [Required]
as was the case here , so that answer doesn't apply to me.我声明的外键没有任何属性,例如[Required]
就像这里的情况一样,所以这个答案不适用于我。 Its just a simple FK:它只是一个简单的 FK:
public int? SomeForeignKeyId { get; set; }
Now a temporary fix for me was to just disable EF validation现在对我来说一个临时解决方法是禁用 EF 验证
Configuration.ValidateOnSaveEnabled = false;
which obviously isn't the best solution.这显然不是最好的解决方案。 So what is the issue here?那么这里的问题是什么?
Found the solution myself (and rather fast lol)自己找到了解决方案(而且相当快,哈哈)
I had this in my model builder我在我的 model 构建器中有这个
modelBuilder.Entity<ForeignModel>()
.HasMany(c => c.Items)
.WithRequired(i => i.ForeignModel)
.HasForeignKey(i => i.SomeForeignKeyId)
.WillCascadeOnDelete(false);
The .WithRequired(i => i.ForeignModel)
obviously declared the column as required so the solution is to change it to .WithOptional(i => i.ForeignModel)
.WithRequired(i => i.ForeignModel)
显然根据需要声明了该列,因此解决方案是将其更改为.WithOptional(i => i.ForeignModel)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.