简体   繁体   中英

Code first The INSERT statement conflicted with the FOREIGN KEY constraint

I just started using Code first approach for creating databases. I have following 3 tables :

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; }
}

Here TagDatabse and User and TagType have 1 to 1 replationship. The fluent API code which i used for this is :

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

Now my issue is whenever i am trying to insert data in TagDatabase i got this exception :

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'.

The TagTypeId property is allowed nulls .so i used HasOptional() in OnModelCreating method.

Cananybody please tell me how to solve this issue and what i am missing here ?

You should make the foreign key property nullable if the corresponding relationship is optional.

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...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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