Click here to Skip to main content
14,268,822 members
Rate this:
Please Sign up or sign in to vote.
See more:
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 AccountHolder and Nominee both have 1 to * replationship with the address. 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 AccountHolder or Nominee 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'.

Can anybody please tell me how to solve this issue and what i am missing here ?
Posted
Updated 1-Jan-14 0:54am
v3

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

Your fluent API has TagTypes option

Quote:
HasOptional(a => a.TagTypes)


But in the model foreign key relationship seems to be mandatory .Either change the Hasoptional to mandatory or make it nullable in the model.

public int? TagTypeID { get; set;}


and/or
public int? CreatedBy { get; set;}
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100