[英]A referential integrity constraint violation occurred Nullable FK
I have a nullable int as a fk in my table as seen below.我的表中有一个可为空的 int 作为 fk,如下所示。 I have made the FK int?.我已经把 FK 变成了 int?。 But if i attempt to save with a null value a get a referencial constraint error?但是,如果我尝试使用空值进行保存,则会出现引用约束错误?
[Table("Tests")]
public class Tests : BaseEntity
{
[MaxLength(255)]
public virtual string TestName { get; set; }
public virtual int? ProjectId { get; set; }
[ForeignKey("ProjectId")]
public virtual Project Project { get; set; }
}
[Table("Project")]
public class Project : BaseEntity
{
[Required, MaxLength(100)]
public virtual string Name { get; set; }
[Required, MaxLength(200)]
public virtual string Type { get; set; }
}
public class BaseEntity
{
[Key, Required]
public virtual int Id { get; set; }
[Required]
public virtual DateTime CreatedDate { get; set; }
}
_testsRepo.InsertOrUpdateAndGetId(test);
Exception :例外 :
System.InvalidOperationException: A referential integrity constraint violation occurred: The property value(s) of 'Project.Id' on one end of a relationship do not match the property value(s) of 'Tests.ProjectId' on the other end. System.InvalidOperationException:发生参照完整性约束冲突:关系一端的“Project.Id”的属性值与另一端“Tests.ProjectId”的属性值不匹配。
So the Issue was in the AutoMapper code I needed the following line所以问题出在 AutoMapper 代码中,我需要以下行
.ForMember(dest => dest.ProductId, opts => opts.MapFrom(src => src.ProductId))
.ForMember(dest => dest.Product, opts => opts.Ignore());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.