Skip to content

OwnsMany primitive type support? #14115

@jasonycw

Description

@jasonycw

Is there a way with the new OwnsMany to allow a entity to own a list of string from another table

Models

public class User
{
    public Guid UserId { get; set; }
    public string Email { get; set; }
    public IEnumerable<Role> Roles { get; set; }
}
public class Role
{
    public string Value { get; set; }
}

DbContext

builder.Entity<User>(m =>
{
    #region Mappings
    m.ToTable("User", "user");
    m.HasKey(x => x.UserId);

    m.OwnsMany(x => x.Roles, b =>
    {
        b.ToTable("UserRole", "user");
        b.Property<Guid>("UserId");
        b.Property<Guid>("RoleAssignmentId");
        b.HasKey("RoleAssignmentId");
        b.Property(x => x.Value)
            .HasColumnName("Role");
        b.HasForeignKey("UserId");
    });
    #endregion
});

The above is working and when we query for the admin user, we need to

_dbContext_.Set<User>().Where(x => x.Role.Value == "Admin")

Is there a way to simplify it to become

public class User
{
    public Guid UserId { get; set; }
    public string Email { get; set; }
    public IEnumerable<string> Roles { get; set; }
}
//--------------------------
builder.Entity<User>(m =>
{
    #region Mappings
    m.ToTable("User", "user");
    m.HasKey(x => x.UserId);

    m.OwnsMany(x => x.Roles, b =>
    {
        b.ToTable("UserRole", "user");
        b.Property<Guid>("UserId");
        b.Property<Guid>("RoleAssignmentId");
        b.HasKey("RoleAssignmentId");
        b.Property(x => x)
            .HasColumnName("Role");
        b.HasForeignKey("UserId");
    });
    #endregion
});

So this could work

_dbContext_.Set<User>().Where(x => x.Role == "Admin")

Further technical details

EF Core version: 2.2
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2017 15.9.3

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions