[英]EF Core - Reuse the same join table entity for several relationships
我想將相同的多對多關系表(FileInEntity)重用於其他幾個對象(課程,演講,游戲),因為它們都可以有文件。 由於我們必須通過創建連接實體來手動創建多對多關系,因此我想將連接實體重用於對象(課程,講座,游戲)。
如果我們看一下表結構,我希望具有以下內容:
課程 :Id,...
講座 :Id,...
游戲 :Id,...
FileInEntity :EntityId(可以是Course.Id,Lecture.Id或Game.Id),FileId
File :Id,...(文件是具有兩種派生類型的基本類類型:圖像和音頻)
當我在.NET Core中嘗試這種方法時,收到以下錯誤消息:
實體類型“ FileInEntities”處於陰影狀態。 有效的模型要求所有實體類型都具有對應的CLR類型。
這有可能嗎?
這是我的設置:
模型庫
public class ModelBase
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
}
Course.cs
[Table("Courses")]
public class Course : ModelBase
{
private ICollection<FileInEntity> IconsInCourse { get; set; } = new List<FileInEntity>();
[NotMapped]
public File Image => IconsInCourse.Select(e => e.File).FirstOrDefault();
}
Lecture.cs
// Same as Course.cs
Game.cs
// Same as Course.cs
FileInEntity.cs
[Table("FilesInEntities")]
public class FileInEntity
{
public Guid FileId { get; set; }
public Guid EntityId { get; set; }
public virtual ModelBase Entity { get; set; }
public virtual File File { get; set; }
}
File.cs
[Table("Files")]
public class File : ModelBase
{
// This is the property for which the error occured
private ICollection<FileInEntity> FileInEntities { get; set; } = new List<FileInEntity>();
public IEnumerable<ModelBase> Entities => FileInEntities.Select(e => e.Entities);
}
FilesInEntitiesMap.cs(關系配置)
builder.HasOne(p => p.Entity)
.WithMany()
.HasForeignKey(k => k.EntityId);
builder.HasOne(p => p.File)
.WithMany()
.HasForeignKey(k => k.FileId);
FileMap.cs
// This is the key to which the error references to
builder.HasMany("FileInEntities")
.WithOne("Entity")
.HasForeignKey("EntityId");
您將無法使用基類ModelBase作為映射類中的對象,因為c#將不知道從db返回的實際類型。 您可以查看每個層次結構繼承的表,但我仍然不確定您是否也可以在映射表中使用它。 這是一篇好文章
如果您的Course.cs,Lecture.cs和Game.cs相同,唯一的區別是類型,則可以將它們組合為一個類,並添加枚舉屬性以設置類型。
public enum EntityType{
Game = 1,
Lecture = 2,
Course = 3
}
public class MyEntity : ModelBase{
private ICollection<FileInEntity> Icons { get; set; } = new List<FileInEntity>();
[NotMapped]
public File Image => Icons.Select(e => e.File).FirstOrDefault();
public EntityType EntityType {get;set;} //course, lecture, or game
}
當您關心類型時,只需使用where子句即可。
確保在DbContext's OnModelCreating
使用Fluent Api
為該表確定One to One relationship
。 (並再次確保選擇了正確的參考屬性)
您的代碼缺少部分。
public class ModelBase
{
[Key]// add for primary key
//set none always for primary keys (because guid has no auto increment)
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
}
[Table("Files")]
public class File : ModelBase
{
//make it public
public ICollection<FileInEntity> FileInEntities { get; set; } = new List<FileInEntity>();
[NotMapped] //set not mapped
public IEnumerable<ModelBase> Entities => FileInEntities.Select(e => e.Entities);
//do it same changes for `Lacture.cs`, `Game.cs` and `Course.cs`...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.