简体   繁体   English

加载具有 1 到 0..1 关系实体框架的实体时出错

[英]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在我的 DBContext 中,关系定义为 1 到 0..1 PhotoData 可能有 0 或 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:现在,我想使用以下命令加载 PhotoData 及其相关的 PhotoBlob:

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.发生这种情况是因为您在PhotoData的构造函数中启动了BlobData 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.我还不知道它会导致这种副作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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