繁体   English   中英

代码优先INSERT语句与FOREIGN KEY约束冲突

[英]Code first The INSERT statement conflicted with the FOREIGN KEY constraint

我刚刚开始使用代码优先方法创建数据库。 我有以下3表:

public class TagDatabase
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TagID { get; set; }
    public string TagName { get; set; }
    public string Description { get; set; }
    public int Count { get; set; }

    [ForeignKey("TagTypes")]
    public virtual int TagTypeID { get; set; }
    public virtual ICollection<TagTypesDb> TagTypes { get; set; }

    [ForeignKey("Users")]
    public virtual int CreatedBy { get; set; }
    public virtual UsersDb Users { get; set; }
}

public class TagTypesDb
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int TagTypeID { get; set; }
    public string TagTypeName { get; set; }
}

public class UsersDb
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserID { get; set; }
    public string UserName { get; set; }
}

这里TagDatabse和User和TagType具有1到1的复制关系。 我为此使用的流畅的API代码是:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<TagDatabase>()
           .HasOptional(a => a.TagTypes)
           .WithMany()
           .HasForeignKey(u => u.TagTypeID);

        modelBuilder.Entity<TagDatabase>()
                    .HasRequired(a => a.Users)
                    .WithMany()
                    .HasForeignKey(u => u.CreatedBy);
}

现在我的问题是,每当我尝试在TagDatabase中插入数据时,都会遇到此异常:

TagDatabase_TagTypes: : Multiplicity conflicts with the referential constraint in Role 'TagDatabase_TagTypes_Target' in relationship 'TagDatabase_TagTypes'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

TagTypeId属性允许为null。因此,我在OnModelCreating方法中使用了HasOptional()。

谁能告诉我如何解决这个问题以及我在这里缺少什么?

如果对应关系是可选的,则应使外键属性为nullable

public class TagDatabase
{
  //sniff...

 [ForeignKey("TagTypes")]
 public virtual int? TagTypeID { get; set; }      //Since TagTypes is optional, this should be nullable
 public virtual ICollection<TagTypesDb> TagTypes { get; set; }

 //sniff...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM