简体   繁体   English

实体框架中的前缀列命名约定

[英]Prefix Column Naming Convention in Entity Framework

Please consider EF6 code-first database. 请考虑EF6代码优先的数据库。 I have: 我有:

public class Base
{
    public int Id { get; set; }
}

public class Desc1 : Base
{
    public string Foo { get; set; }
}

public class Desc2 : Base
{
    public int? Foo { get; set; }
}

I want table Base to have three columns (in a automatically way) : 我希望表Base具有三列(以自动方式):

Base_Id INT NOT NULL
Desc1_Foo VARCHAR(MAX) NULL
Desc2_Foo INT NULL

I mean, prefixed by its class name. 我的意思是,以其类名开头。 I know I can use EntityTypeConfiguration to do that, but my database has 150 tables and I can't configure each column. 我知道我可以使用EntityTypeConfiguration来做到这一点,但是我的数据库有150个表,因此无法配置每一列。

So I tried to use a naming convention: 因此,我尝试使用命名约定:

public class PrefixConvention : IStoreModelConvention<EdmProperty>
{
    public void Apply(EdmProperty property, DbModel model)
    {
        property.Name = property.DeclaringType.Name + "_" + property.Name;
    }
}

...

modelBuilder.Conventions.Add(new PrefixConvention());

but property.DeclaringType.Name shows me only Base and not Desc1 or Desc2 , and it always creates this: 但是property.DeclaringType.Name仅向我显示Base ,而不向我显示Desc1Desc2 ,它始终会创建以下内容:

Base_Id INT NOT NULL
Base_Foo VARCHAR(MAX) NULL
Base_Foo1 INT NULL

I investigated EdmModel class, but I can't find a way to get the class name that originates the field in the table! 我研究了EdmModel类,但是找不到找到源自表中字段的类名称的方法!

Ok, I developped my own PrefixConvention. 好的,我开发了自己的PrefixConvention。 To use it: 要使用它:

modelBuilder.Conventions.Add(new PrefixConvention());

And here, PrefixConventionclass : 在这里, PrefixConventionclass

using System.Collections.Generic;
using System.Data.Entity.Core.Mapping;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;

namespace Habitus.Toolkit.Database
{
    public class PrefixConvention : IStoreModelConvention<EdmProperty>
    {
        public void Apply(EdmProperty property, DbModel model)
        {
            if (property.Name == "Id" || property.Name == "Discriminator" || property.DeclaringType.IsView()) return;

            var fragments = model
                .ConceptualToStoreMapping
                .EntitySetMappings
                .SelectMany(esm => esm.EntityTypeMappings)
                .SelectMany(etm => etm.Fragments)
                .Where(f => f.StoreEntitySet.ElementType == property.DeclaringType)
                .ToList();

            var propertyMappings = fragments
                .SelectMany(f => f.PropertyMappings)
                .ToList();

            var path = GetPropertyPath(property, propertyMappings);
            if (path?.Any() == false)
            {
                throw new System.Exception($"Can't process property {property.DeclaringType.FullName}.{property.Name}");
            }

            var first = path.First();
            var names = path.Select(pm => pm.Name).ToList();
            property.Name = $"{first.DeclaringType.Name}__{string.Join("_", names)}";
        }

        private List<EdmProperty> GetPropertyPath(EdmProperty property, List<PropertyMapping> propertyMappings)
        {
            var result = new List<EdmProperty>();

            var scalarPropertyMapping = propertyMappings
                .OfType<ScalarPropertyMapping>()
                .Where(pm => pm.Column == property)
                .FirstOrDefault();

            if (scalarPropertyMapping != null)
            {
                result.Add(scalarPropertyMapping.Property);
            }

            else
            {
                var complexPropertyMappings = propertyMappings
                    .OfType<ComplexPropertyMapping>()
                    .ToList();

                foreach (var complexPropertyMapping in complexPropertyMappings)
                {
                    var recursivePropertyMappings = complexPropertyMapping
                        .TypeMappings
                        .SelectMany(tm => tm.PropertyMappings)
                        .ToList();

                    var recursiveResult = GetPropertyPath(property, recursivePropertyMappings);
                    if (recursiveResult.Any())
                    {
                        result.Add(complexPropertyMapping.Property);
                        result.AddRange(recursiveResult);
                        break;
                    }
                }
            }

            return result;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM