Entity Framework Code First - 来自多个表的一对多关系
Entity Framework Code First - One to Many relations from multiple tables
我有一个 BlobEntity table,其中包含许多其他 table 的文件路径(tableX,tableY,tableZ,等等...)在我的应用程序中。
所有其他 table 与 BlobEntity table 之间的关系是一对多。
示例:
tableX -> BlobTable (OTM)
tableY -> BlobTable (OTM)
tableZ -> BlobTable (OTM)
关系是:
public virtual ICollection<BlobEntity> BlobEntity { get; set; }
我不确定这是否是个问题,但是 entity framework Code First 在 BlobEntity table 中为每个源 table 创建了一个新的 FK 列 table。
在我的例子中,BlobEntity 包含三个 FK 列,用于 tableX、tableY 和 tableZ。
为了提高效率,我宁愿在 BlobEntity 中创建一列,其中包含源 tables 的 FK。
合理吗?
请指教...
谢谢。
不,即使在普通的 SQL 中也不能这样做。
您可以有一个指向多个 table 的前键;这就是为什么你需要
三列。
如果你想做这样的 "trick",你必须手动管理关系(我的意思是,没有真正的 FK),但你不能将它映射到 EF。
这个呢?
public class EntityA
{
public int Id { get; set; }
public int MyFileID {get;set;}
public virtual MyFiles MyFile { get; set; }
}
public class EntityB
{
public int Id { get; set; }
public int MyFileID {get;set;}
public virtual MyFiles MyFile { get; set; }
}
public class MyFiles
{
public MyFiles()
{
// ReSharper disable once VirtualMemberCallInContructor
FilesForEntityA = new List<EntityA>();
// ReSharper disable once VirtualMemberCallInContructor
FilesForEntityB = new List<EntityB>();
}
public int Id { get; set; }
public int? EntityAId {get;set;}
public int? EntityBId {get;set;}
public virtual ICollection<EntityA> FilesForEntityA { get; set; }
public virtual ICollection<EntityB> FilesForEntityB { get; set; }
}
这样您就可以拥有 FK,并且可以轻松地管理多个实体。
显然,如果每个实体都有很多文件,则可以采用 N 对 N 关系,例如 this.
我有一个 BlobEntity table,其中包含许多其他 table 的文件路径(tableX,tableY,tableZ,等等...)在我的应用程序中。
所有其他 table 与 BlobEntity table 之间的关系是一对多。
示例:
tableX -> BlobTable (OTM)
tableY -> BlobTable (OTM)
tableZ -> BlobTable (OTM)
关系是:
public virtual ICollection<BlobEntity> BlobEntity { get; set; }
我不确定这是否是个问题,但是 entity framework Code First 在 BlobEntity table 中为每个源 table 创建了一个新的 FK 列 table。
在我的例子中,BlobEntity 包含三个 FK 列,用于 tableX、tableY 和 tableZ。
为了提高效率,我宁愿在 BlobEntity 中创建一列,其中包含源 tables 的 FK。
合理吗?
请指教...
谢谢。
不,即使在普通的 SQL 中也不能这样做。 您可以有一个指向多个 table 的前键;这就是为什么你需要 三列。
如果你想做这样的 "trick",你必须手动管理关系(我的意思是,没有真正的 FK),但你不能将它映射到 EF。
这个呢?
public class EntityA
{
public int Id { get; set; }
public int MyFileID {get;set;}
public virtual MyFiles MyFile { get; set; }
}
public class EntityB
{
public int Id { get; set; }
public int MyFileID {get;set;}
public virtual MyFiles MyFile { get; set; }
}
public class MyFiles
{
public MyFiles()
{
// ReSharper disable once VirtualMemberCallInContructor
FilesForEntityA = new List<EntityA>();
// ReSharper disable once VirtualMemberCallInContructor
FilesForEntityB = new List<EntityB>();
}
public int Id { get; set; }
public int? EntityAId {get;set;}
public int? EntityBId {get;set;}
public virtual ICollection<EntityA> FilesForEntityA { get; set; }
public virtual ICollection<EntityB> FilesForEntityB { get; set; }
}
这样您就可以拥有 FK,并且可以轻松地管理多个实体。 显然,如果每个实体都有很多文件,则可以采用 N 对 N 关系,例如 this.