c# - C# Fluent API 将两个属性映射到同一列
问题描述
我的问题实际上很简单:
这是 MySQL 表"ClubCategory"。如您所见,它将俱乐部与类别联系起来。
+------------+------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------+------+-----+---------+-------+
| CategoryId | int | NO | PRI | NULL | |
| ClubId | int | NO | PRI | NULL | |
+------------+------+------+-----+---------+-------+
问题如下:我的支持 C# 类必须实现一个接口,该接口指定一个名为OtherId
where的附加属性,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.CategoryId
或ClubCategory.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
链中似乎告诉实体框架该值是由数据库在保存时自动生成的。因此,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();
推荐阅读
- parsing - 从数组中的数组中获取数据的问题
- three.js - 为什么three.js pointcloud在mac和windows(Intel HD graphics 4000)之间的渲染不一样?
- android - 如何从android中的资产文件夹链接Web视图中的多个HTML页面?
- c# - 在 EF6 中复制对象,但主键除外
- shopify - Shopify 在产品系列页面上显示平均或总评分徽章
- javascript - 如何(sinon)存根外部模块功能?
- python - 从 CSV 中的 JSON 中提取数据
- asp.net - 对 dotnet 代码的 LINQ 查询以及 concat 将如何在此处工作
- android - 运行“npm run android”时无法从“11.0.1”确定 java 版本
- javascript - 灯箱内的 AMP 轮播未打开录制/点击的图像