简体   繁体   English

发生参照完整性约束冲突 Nullable FK

[英]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.

相关问题 发生了参照完整性约束违规 - A referential integrity constraint violation occurred 发生参照完整性约束违规 - Referential integrity constraint violation occurred 错误“发生了参照完整性约束冲突” - Error “A referential integrity constraint violation occurred” 尝试将FK设置为​​null时,引用完整性约束违规 - Referential Integrity Constraint violation when attempting to set a FK to null 发生参照完整性约束冲突。 更新EF时 - A referential integrity constraint violation occurred. When Updating EF 向EF添加新实体时出错:发生了参照完整性约束违规 - Error when adding new entity to EF : A referential integrity constraint violation occurred 尝试在Entity Framework中进行更新时出现错误“发生了引用完整性约束冲突” - Error “A referential integrity constraint violation occurred” when trying update in Entity Framework 实体框架迁移-违反参照完整性约束 - Entity Framework Migrations - A referential integrity constraint violation EF 6 Code First,使用包含在导航属性上的外键ID更改会导致“发生引用完整性约束违规”错误 - EF 6 Code First, changing a Foreign Key Id with an Include on navigation property causes “A referential integrity constraint violation occurred” error 保存包含列表的对象会产生“违反参照完整性约束” - Saving an Object that contains a list gives “referential integrity constraint violation”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM