简体   繁体   中英

Error in loading entity with 1 to 0..1 relationship Entity Framework

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?

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.

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