繁体   English   中英

在实体框架中的拥有实体中配置多对一关系

[英]Configure a many to one relationship in a Owned Entity in Entity Framework

我有一个 class 是数据库中的一个实体并拥有一个拥有的实体:

public class EntityOne
{
        public int Id { get; set; }
        public OwnedEntity OwnedEntity { get; set; }
}

我拥有一个包含另一个持久实体类型的列表的拥有实体:

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

这是EntityTwo:

public class EntityTwo
{
        public int Id { get; set; }
 
        // all other properties
}

我需要将 EntityOne 和 EntityTwo 之间的关系创建为多对一,但属性导航在我拥有的实体中。 我怎样才能做到这一点?

我试图创建我拥有的实体的属性导航,如下所示:

public class EntityTwo
{
        public int Id { get; set; }

        public OwnedEntity OwnedEntity { get; set; }

        public int OwnedEntityId { get; set; }

        // all other properties
}

和 map:

builder.HasOne(prop => prop.OwnedEntity)
                .WithMany(prop => prop.EntityTwo)
                .HasForeignKey(prop => prop.OwnedEntityId);

但是我得到了一个错误,因为 ef 试图将我拥有的实体作为实体表。

然后,我尝试引用父实体:

public class EntityTwo
{
            public int Id { get; set; }
    
            public EntityOne EntityOne { get; set; }
    
            public int EntityOneId { get; set; }
    
            // all other properties
}

并具有内部属性的映射:

builder.HasOne(prop => prop.EntityOne.OwnedEntity)
                .WithMany(prop => prop.EntityTwo)
                .HasForeignKey(prop => prop.EntityOne.OwnedEntityId);

但它没有用,我得到另一个 ef 错误:

Error: The expression 'prop => prop.EntityOne.OwnedEntity' is not a valid member access expression. The expression should represent a simple property or field access: 't => t.MyProperty'. (Parameter 'memberAccessExpression')

那么,有没有办法建立这种关系呢?

对于那些想知道我如何解决它的人,我使用OwnsMany在实体一的 map 配置中完成了所有操作。 首先,我将 EntityTwo 的一对多引用更改为 OwnedEntity:

public class EntityTwo
{
            public int Id { get; set; }
    
            public OwnedEntity OwnedEntity { get; set; }
    
            public int OwnedEntityId { get; set; }
    
            // all other properties
}

然后,我制作了这个 map(EntityOne 的构建器):

builder.OwnsOne(prop => prop.OwnedEntity, subBuilder =>
{
    // all map configurations of OwnedEntity

    subBuilder.OwnsMany(prop => prop.EntityTwo, ownedBuilder =>
    {
        ownedBuilder.HasOne(prop => prop.EntityTwo)
        .WithMany(prop => prop.OwnedEntity)
        .HasForeignKey(prop => prop.EntityTwoId);

        // all map configurations of EntityTwo
    }
}

而已。

暂无
暂无

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

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