Nullable FK发生了引用完整性约束违规

时间:2016-10-10 08:20:07

标签: c# .net entity-framework foreign-keys

我在表格中有一个可以为空的int作为fk,如下所示。我做了FK int?。但是,如果我尝试使用空值保存,则获得参考约束错误?

  [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);

例外:

  

System.InvalidOperationException:参照完整性约束   发生违规:一端是“Project.Id”的属性值   关系的属性值与的属性值不匹配   另一端是'Tests.ProjectId'。

1 个答案:

答案 0 :(得分:1)

所以问题出在AutoMapper代码中,我需要以下一行

.ForMember(dest => dest.ProductId, opts => opts.MapFrom(src => src.ProductId))
.ForMember(dest => dest.Product, opts => opts.Ignore());