在 EF Core 中分解结构?

假设我有以下课程:


struct Vector

{

    public float X { get; set; }

    public float Y { get; set; }

    public float Z { get; set; }

}


class Player

{

    public string Name { get; set; }

    public Vector Position { get; set; }

}

我如何在实体框架(核心)中配置它,使其映射到 Name、PositionX、PositionY、PositionZ?


这是用于代码生成目的,所以我不希望用户必须在考虑 EF 的情况下创建他们的 POCO(它也可以发送到很多其他语言!)


慕桂英4014372
浏览 181回答 3
3回答

慕姐4208626

目前(EF Core 3)不支持。但是,有一个关于它的 GitHub 问题,看起来 structs-as-owned-types 已被未来版本接受:https://github.com/dotnet/efcore/issues/9906

长风秋雁

正在寻找同样的东西,并遇到了这个问题。以为我会发布我发现的内容:EF Core 团队建议将其作为 JSON 存储在您的数据库中并使用自定义值转换器:modelBuilder.Entity<Order>()&nbsp; &nbsp; .Property(e => e.Vector)&nbsp; &nbsp; .HasConversion(&nbsp; &nbsp; &nbsp; &nbsp; v => JsonSerializer.Serialize(v, null),&nbsp; &nbsp; &nbsp; &nbsp; v => JsonSerializer.Deserialize<Vector>(v, null));虽然不理想。

慕桂英3389331

对于 Entity Framework Core,您所描述的称为拥有实体配置是这样的:modelBuilder.Entity<Player>()&nbsp; &nbsp; .OwnsOne(p => p.Position);
打开App,查看更多内容
随时随地看视频慕课网APP