投影到某些模型时在 EF Core 中强类型化 id

问题描述 投票:0回答:1

我尝试在具有强类型 ID 的模型上查询 Postgresql DB 并投影到模型。

无法理解为什么查询不起作用。

它抛出这个异常:

未处理的异常。系统.InvalidOperationException: “EF.Property(u3.Id, "ClientId")”的翻译失败。 查询源不是实体类型,或者实体类型上不存在指定的属性。

如果我从查询中删除强类型 ID 并使用普通 Guid,查询将正确执行并从数据库返回数据。

public class Program
{
    public static void Main()
    {
        using var context = new EntityContext();

        var query = (from client in context.Clients
            let managers = from managerId in client.ManagerIds
                join user in context.Users on managerId equals user.Id
                select new { user.Id, user.Name }
            select new { client, managers }).ToList();
    }
}

public record UserId(Guid Value);
public record ClientId(Guid Value);

public class Client
{
    public ClientId Id { get; set; }
    public ICollection<UserId> ManagerIds { get; set; } = new List<UserId>();
}

public record User(UserId Id, string Name);

public class EntityContext : DbContext
{
    public DbSet<Client> Clients { get; set; }
    public DbSet<User> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>().HasKey(x => x.Id);
        modelBuilder.Entity<User>()
            .Property(x => x.Id)
            .HasConversion(x => x.Value, x => new UserId(x));

        modelBuilder.Entity<Client>().HasKey(x => x.Id);
        modelBuilder.Entity<Client>()
            .Property(x => x.Id)
            .HasConversion(x => x.Value, x => new ClientId(x));
        modelBuilder.Entity<Client>()
            .OwnsMany(
                client => client.ManagerIds, 
                ownedNavigationBuilder =>
                {
                    ownedNavigationBuilder
                        .WithOwner()
                        .HasForeignKey("ClientId");
                    ownedNavigationBuilder
                        .Property(x => x.Value)
                        .HasColumnName("ManagerId");
                }
            );
    }
}
c# entity-framework-core owned-types
1个回答
0
投票

我不是 100% 确定,但这种关系看起来并不正确:

        modelBuilder.Entity<Client>()
            .OwnsMany(
                client => client.ManagerIds, 
                ownedNavigationBuilder =>
                {
                    ownedNavigationBuilder
                        .WithOwner()
                        .HasForeignKey("ClientId");
                    ownedNavigationBuilder
                        .Property(x => x.Value)
                        .HasColumnName("ManagerId");
                }
            );

OwnsMany
/
HasMany
用于实体之间的关系,因此我希望客户端有一个
ICollection<User> Managers { get; } = [];
而不是 UserId 的集合。 EF 期望记录是一个实体而不是 GUID。我怀疑 EF 可以在客户端行中存储 GUID 列表,但正确规范化的多对多关系会更好。

© www.soinside.com 2019 - 2024. All rights reserved.