1

I have the following parent-child relationship:

Parent entity:

[Table("PHOTO_DATA")]
public class PhotoData
{
    public PhotoData()
    {
        PhotoBlob = new BlobData();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("PHOTO_N")]
    public long IdNumber { get; set; }

    ...

    public virtual BlobData PhotoBlob { get; set; }
}

Child entity:

[Table("BLOB_DATA")]
public class BlobData
{
    [Key]
    [Column("PHOTO_N")]
    public long IdNumber { get; set; }

    [Column("FILE_IM", TypeName = "BLOB")]
    public byte[] FileImage { get; set; }

    public virtual PhotoData Photo { get; set; }
}

In my DBContext, the relationship is defined has 1 to 0..1 PhotoData may have 0 or 1 BlobData

modelBuilder.Entity<PhotoData>()
            .HasOptional(photo => photo.PhotoBlob)
            .WithRequired(blob => blob.Photo);

Now, I want to load PhotoData with its related PhotoBlob, using the following command:

var data = dbcontext.PhotoDatas.Include(x => x.PhotoBlob).Where(s => s.IdNumber == id).FirstOrDefault();

And I get the following error:

Multiplicity constraint violated. The role 'PhotoData_PhotoBlob_Target' of the relationship 'Data.PhotoData_PhotoBlob' has multiplicity 1 or 0..1.

How to resolve the issue?

rcs
  • 6,713
  • 12
  • 53
  • 75

1 Answers1

0

The cause of this issue isn't obvious. It happens because you initiate BlobData in PhotoData's constructor. If I do that in my own environment I get the same exception.

As I explained here, it's never a good idea to initiate reference properties in constructors of entity classes. I didn't know yet that it caused this side effect.

Gert Arnold
  • 105,341
  • 31
  • 202
  • 291