EF代码首先实现接口属性 [英] EF Code First implemented interface property

查看:92
本文介绍了EF代码首先实现接口属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型。

interface IKeywordedEntity
{
    IEntityCollection<Keyword> Keywords { get; }
}
class Foo : EntityBase, IKeywordedEntity
{
     public virtual IEntityCollection<Keyword> Keywords { get { ... } }
}
class Bar : EntityBase, IKeywordedEntity
{
     public virtual IEntityCollection<Keyword> Keywords { get { ... } }
}

我想编写一个扩展方法 OnModelCreating 中的每一个都自动处理关键字。

I want to write an extension method that takes care of the keywords automatically for each of these in OnModelCreating.

public static void WithKeywords<TEntityType>(this EntityTypeConfiguration<TEntityType> 
   entityTypeConfiguration) where TEntityType : EntityBase, IKeywordedEntity
{
    entityTypeConfiguration.HasMany(e => e.Keywords).WithMany();
}

所以我在 OnModelCreating

So I invoke it like this in OnModelCreating.

modelBuilder.Entity<Foo>.WithKeywords();
modelBuilder.Entity<Bar>.WithKeywords();

但是,我得到以下异常:

However, I get the following exception:

导航属性关键字不是
'Foo'上声明的属性。验证它没有被明确排除在模型
之外,并且它是一个有效的导航属性。

The navigation property 'Keywords' is not a declared property on type 'Foo'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.

我可以请允许此扩展方法工作?

What can I do to allow this extension method to work?

推荐答案

在阅读Ladislav的答案后,我决定手动写表达式。 >

After reading Ladislav's answer, I decided to manually write the expression.

    public static void WithKeywords<TEntityType>(this EntityTypeConfiguration<TEntityType> entityTypeConfiguration)
        where TEntityType : EntityBase, IKeywordedEntity
    {
        var rootExpression = Expression.Parameter(typeof (TEntityType));
        var expression = Expression.Property(rootExpression, "Keywords");

        entityTypeConfiguration.HasMany(Expression.Lambda<Func<TEntityType, ICollection<Keyword>>>(expression, rootExpression)).WithMany();
    }

这篇关于EF代码首先实现接口属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆