2

我的问题实际上很简单:

这是 MySQL 表"ClubCategory"。如您所见,它将俱乐部与类别联系起来。

+------------+------+------+-----+---------+-------+
| Field      | Type | Null | Key | Default | Extra |
+------------+------+------+-----+---------+-------+
| CategoryId | int  | NO   | PRI | NULL    |       |
| ClubId     | int  | NO   | PRI | NULL    |       |
+------------+------+------+-----+---------+-------+

问题如下:我的支持 C# 类必须实现一个接口,该接口指定一个名为OtherIdwhere的附加属性,OtherId它只是CategoryId.

该类如下所示

public class ClubCategory : IClubFilterLinker
{
    private int _categoryId;

    public int ClubId { get; set; }

    public int CategoryId
    {
        get => _categoryId;
        set => _categoryId = value;
    }

    public int OtherId
    {
        get => _categoryId;
        set => _categoryId = value;
    }
}

我基本上需要能够使用ClubCategory.CategoryIdClubCategory.OtherId访问相同的数据库列CategoryId

我尝试的 Fluent API 映射如下所示:

modelBuilder.Entity<ClubCategory>()
    .Property(nameof(_categoryId))
    .HasColumnName("CategoryId")
    .HasColumnType("INT")
    .IsRequired();

modelBuilder.Entity<ClubCategory>()
    .Property(cc => cc.CategoryId)
    .HasField(nameof(_categoryId))
    .UsePropertyAccessMode(PropertyAccessMode.Field);

modelBuilder.Entity<ClubCategory>()
    .Property(cc => cc.OtherId)
    .HasField(nameof(_categoryId))
    .UsePropertyAccessMode(PropertyAccessMode.Field);

但是,在访问此类的实例时生成的 MySQL 查询

SELECT `c`.`ClubId`, `c`.`CategoryId`, `c`.`OtherId`, `c`.`CategoryId`
FROM `club2category` AS `c`

显然是彻底坏掉了。它不仅指定CategoryId了两次,而且还尝试访问OtherId数据库中不存在的虚构列:|

那么我需要在 Fluent API 中进行哪些更改才能成功地将两个属性映射到同一个 MySQL 列?或者有可能吗?任何帮助将不胜感激:)

4

1 回答 1

0

通过PropertyBuilder一种方法的所有智能感知建议引起了我的注意:ValueGeneratedOnAddOrUpdate()

从文档中:

将属性配置为在保存新实体或现有实体时生成一个值。

将此添加到PropertyBuilder链中似乎告诉实体框架该值是由数据库在保存时自动生成的。因此,EF 在插入或更新期间将此属性从其查询中排除。基本上允许您将这些“只读”属性中的多个映射到同一个数据库列并在您的查询中使用它们,这正是我在我的问题中所要求的。这也允许我删除私有支持字段。

我的ClubCategory班级现在看起来像这样:

public class ClubCategory : IClubFilterLinker
{
    public int ClubId { get; set; }

    public int CategoryId { get; set; }

    public int OtherId { get; set; }
}

这是相应的 Fluent API 映射:

modelBuilder.Entity<ClubCategory>()
    .Property(cc => cc.CategoryId)
    .HasColumnName("CategoryId")
    .HasColumnType("INT")
    .IsRequired();

modelBuilder.Entity<ClubCategory>()
    .Property(cc => cc.OtherId)
    .HasColumnName("CategoryId")
    .HasColumnType("INT")
    // Prevent EF from using this property in insert / update statements.
    .ValueGeneratedOnAddOrUpdate();
于 2020-11-04T16:08:33.547 回答