Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define optional self-referencing one-many relationship with Fluent Api

public class Attribute
{
    [Key]
    public int AttributeId { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    public int ValueAttributeId { get; set; }
    public Attribute ValueAttribute { get; set; }

    public IList<Attribute> ValueAttributes { get; set; }
}

  modelBuilder.Entity<Attribute>()
     .HasOptional(a => a.ValueAttribute)
     .WithMany(a => a.ValueAttributes)
     .HasForeignKey(a => a.ValueAttributeId);

\tSystem.Data.Entity.Edm.EdmAssociationType: : Multiplicity conflicts with the referential constraint in Role 'Attribute_ValueAttribute_Target' in relationship 'Attribute_ValueAttribute'. Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.

Aaaaahhhh.....

like image 350
Ian Warburton Avatar asked Dec 27 '22 05:12

Ian Warburton


1 Answers

public int ? ValueAttributeId { get; set; }

... the property needed to be null-able.

like image 191
Ian Warburton Avatar answered Apr 26 '23 13:04

Ian Warburton