问题描述
我的问题实际上很简单:
这是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.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);
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();