简体   繁体   English

Object 参考未设置错误 EF6 拥有的实体

[英]Object Reference Not Set Error EF6 Owned Entity

I am getting an object reference not set to an instance of an object error when running add-migration运行 add-migration 时出现 object 引用未设置为 object 错误的实例

I'm trying to add a reference to an entity that also just so happens to be the same as the owning entity type我正在尝试添加对实体的引用,该实体也恰好与拥有实体类型相同

public class OwningEntity {
    public OwningEntity(){
        OwnedEntities = new List<OwnedEntity>();
    }

    public int Id {get;set;}
    public List<OwnedEntity> OwnedEntities {get;set;}
}

[Owned]
public class OwnedEntity {
    string Name {get;set;}
    public int AnotherOwningEntityNotTheParentOfThisId {get;set}
    public OwningEntity AnotherOwningEntityNotTheParentOfThis {get;set;}
} 

I can see how this confuses EF6...but I'm not sure what I could add in the model builder to help clarify this我可以看到这如何混淆 EF6 ......但我不确定我可以在 model 构建器中添加什么来帮助澄清这一点

So far all I have is:到目前为止,我所拥有的是:

modelBuilder<OwningEntity>().HasKey(o => o.Id)
modelBuilder.Entity<OwningEntity>().OwnsMany(o => o.OwnedEntity)

And the error is:错误是:

System.NullReferenceException: Object reference not set to an instance of an object. System.NullReferenceException:Object 引用未设置为 object 的实例。 at Microsoft.EntityFrameworkCore.Metadata.Internal.InternalRelationshipBuilder.IsWeakTypeDefinition(ConfigurationSource configurationSource)在 Microsoft.EntityFrameworkCore.Metadata.Internal.InternalRelationshipBuilder.IsWeakTypeDefinition(ConfigurationSource 配置源)

Try this:尝试这个:

public class OwningEntity {
    [Key]
    public int Id {get;set;}
    [InverseProperty(nameof(OwnedEntity.OwningEntity))]
    public List<OwnedEntity> OwnedEntities {get;set;}
}

[Owned]
public class OwnedEntity {
    [Key]
    public int Id {get; set;}
    string Name {get;set;}
    public int OwningEntityId {get;set}
    [ForeignKey(nameof(OwningEntityId))]
    [InverseProperty("OwnedEntities")]
    public OwningEntity OwningEntity  {get;set;}
} 

and db context:和数据库上下文:

public DbSet<OwnedEntity > OwnedEntities { get; set; }
public DbSet<OwningEntity > OwningEntities{ get; set; }

....

modelBuilder.Entity<OwnedEntity>(entity =>
            {
                entity.HasOne(d => d.OwningEntity)
                   .WithMany(p => p.OwnedEntities)
                   .HasForeignKey(d => d.OwningEntity)
                   .OnDelete(DeleteBehavior.ClientSetNull);
                  
            });

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

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