EF多个DbContexts使用公共基类

时间:2014-04-18 14:35:58

标签: entity-framework

我首先使用EF 6.1代码,并且在单独的库插件中有许多dbcontext模型。我还有一个共同的基类模型,它也在一个单独的核心库中。我正在使用TPT继承。 我想知道如何编写插件模型,以便它们不需要具有公共基类表。这就是我的插件上下文现在的样子:

public partial class NewsModel : DbContext
{
    public NewsModel()
        : base( "name=NewsModel" )
    {
    }

    public NewsModel( String connectionString )
        : base( connectionString )
    {
    }

    public virtual DbSet<ContentBase> ContentBaseSet { get; set; }
    public virtual DbSet<Tag> Tags { get; set; }

    public virtual DbSet<NewsItem> News { get; set; }
    public virtual DbSet<NewsFeed> NewsFeeds { get; set; }

    protected override void OnModelCreating( DbModelBuilder modelBuilder )
    {
    }

我想删除ContentBaseSet,因为在发出add-migration命令时,所有内容类型(在其他插件库和核心中声明)都会添加到迁移中。我希望NewModel的添加迁移能够排除ContentBase以及从中继承的所有其他类型。 我确信通过使用DbModelBuilder修改插件dbcontext可以做到这一点。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我使用自定义属性类和自定义约定来取消映射模块化插件内容类型库中不需要的实体(所有内容类型都是从ContentBase抽象类派生的)。

这是属性类。

[AttributeUsage( AttributeTargets.Class )]
public class CoreContentEntity : Attribute
{
}

每个核心内容类型都有此属性。

[Table("cms_Events")]
[CoreContentEntity]
public partial class Event : ContentBase
{

现在为每个插件内容类型(dbcontext类)添加自定义约定。

    protected override void OnModelCreating( DbModelBuilder modelBuilder )
    {
        modelBuilder.Conventions.Add<UnmapCoreEntitiesConvention>();
    }

最后,这是自定义约定。

public class UnmapCoreEntitiesConvention : Convention
{
    public UnmapCoreEntitiesConvention()
    {
        Types()
            .Where( t => t.CustomAttributes.Any( n => n.AttributeType == typeof( CoreContentEntity ) ) )
            .Configure( config => config.Ignore() );
    }
}

为了使TPT继承在插件内容类中工作,我仍然需要在模型dbcontext类中包含核心ContentBase类。如果有人知道如何解决我想知道的问题(每个插件类型都有自己的表,而ContentBase类必须有自己的表)。

相关问题