gpt4 book ai didi

asp.net - Entity Framework 类类型属性到蛇案例

转载 作者:行者123 更新时间:2023-12-04 15:34:44 25 4
gpt4 key购买 nike

我想将 RoomLocation 类型的 Location 映射到

Floor -> location_floor,
Building -> location_building,
Room -> location_room

房间.cs

public class Room
{
[Key]
public Guid Id { get; set; }
public string Title { get; set; }
public RoomLocation Location { get; set; }

public DateTime CreationDate { get; set; }
public DateTime ModificationDate { get; set; }
}

public class RoomLocation
{
public int Floor { get; set; }
public int Building { get; set; }
public int Room { get; set; }
}

数据库图

Database diagram

注意:在一个较旧的项目中,我忘记添加 builder.HasKey 而它确实有效 我查看了日志, Entity Framework 现在将查询转换为 user_ 因为我忘记了到底发生了什么,我无法重做这种情况。

我正在使用带有 SnakeCaseNamingConvention 的 Npgsql Entity Framework 。

最佳答案

The following guidance is for Entity Framework, not EF Core. It is still relevant guidance for .Net Framework implementations.


您在这里询问的 EF 功能是通过使用 Complex Types 来实现的。 .

  • A ComplexType doesn't have keys and therefore cannot exist independently.
  • It can only exist as properties of entity types or other complex types.
  • It cannot participate in associations and cannot contain navigation properties.
  • Complex type properties cannot be null.
  • Scalar properties of complex objects can be null.

通过将 RoomLocation 标记为复杂类型,EF 不会创建或映射到数据库中的单独表,而是映射到表中的字段包含复杂类型属性的类型。

您可以使用 Fluent API 来做到这一点或 Data Annotations然而,当您使用 KeyAttribute 时,此示例让我们继续数据注释(也称为 Attribute 表示法)

所以让 RoomLocation 成为一个复杂类型:

[ComplexType]
public class RoomLocation
{
public int Floor { get; set; }
public int Building { get; set; }
public int Room { get; set; }
}

数据库字段的默认命名约定意味着以下默认数据库字段映射将用于此表:

NOTE: this is MS SQL Server Syntax, similar types would be used in Postgres, the names of the fields here are important for this discussion.

Id UniqueIdentifier NOT NULL,
Title NVarChar(MAX),
Location_Floor INT NOT NULL,
Location_Building INT NOT NULL,
Location_Room INT NOT NULL,
CreationDate DateTime2 NOT NULL
ModificationDate DateTime2 NOT NULL

您可以通过 Fluent API 使用约定或特定映射将这些字段映射到不同的命名字段。

NOTE: If the casing of your fields is slightly different (Caml, Lower or Upper case) EF will still resolve this mapping and should still work against Postgres database fields that are all lower case like your example

item.Location.Floor -> location_floor,
item.Location.Building -> location_building,
item.Location.Room -> location_room

关于asp.net - Entity Framework 类类型属性到蛇案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60131588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com