C#Fluent API将两个属性映射到同一列

问题描述

我的问题实际上很简单:

这是MysqL“ ClubCategory” 。如您所见,它会将俱乐部链接到类别。

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

问题如下:我的支持C#类必须实现一个接口,该接口指定名为OtherId的附加属性,其中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列? 还是有可能吗?任何帮助将不胜感激:)

解决方法

浏览PropertyBuilder的所有智能建议时,一种方法引起了我的注意:ValueGeneratedOnAddOrUpdate()

从文档中:

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

将其添加到PropertyBuilder链似乎可以告诉Entity Framework该值是数据库在保存时自动生成的。因此,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();

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...