仅为实体框架7中的整个模型映射一次公共属性

时间:2015-12-14 17:20:33

标签: c# .net entity-framework entity-framework-core

在我的域模型中,我尝试仅为属于 EntityBase 的子类的实体设置公共属性的映射。为此,我尝试使用 IsAssignableFrom 进行过滤,但它没有给出结果,也没有为这些属性进行映射。

有关如何解决IsAssignableFrom问题或任何其他验证实体层次结构的方法的建议将不胜感激。

        protected override void OnModelCreating(ModelBuilder modelBuilder)
                {
                    var types = modelBuilder.Model.GetEntityTypes().Where( entity =>   
            typeof(Domain.Core.Entity).IsAssignableFrom(entity.GetType()));
            foreach (var entType in types)
                    {                 
                         entType.AddProperty("CreatedBy", typeof (string));
                         entType.AddProperty("ModifiedBy", typeof(string));
                         entType.AddProperty("CreatedOn", typeof(DateTime));
                         entType.AddProperty("LastModifiedOn", typeof(DateTime));
                         entType.AddProperty("RowVersion", typeof(byte[]));
                    }
                }

2 个答案:

答案 0 :(得分:1)

I think IsAssignableFrom is not used correctly in your case:

typeof(Domain.Core.EntityBase).IsAssignableFrom(entity.GetType()) 

should be used if your intention is to iterate through all types that derive (directly on indirectly) from EntityBase

答案 1 :(得分:0)

您走在正确的轨道上,但我建议您应该使用纯反射而不是模型来获取实体类型。尝试这样的事情:

        var asm = Assembly.Load("Domain.Core");
        foreach(var type in asm.GetTypes())
        {
            if(typeof(Domain.Core.Entity).IsAssignableFrom(type))
            {
                var builder = modelBuilder.Entity(type);
                builder.Property(typeof(string), "CreatedBy");
                // ...
            }
        }