EF 6,代码第一个联结表名称 [英] EF 6, code first junction table name

查看:62
本文介绍了EF 6,代码第一个联结表名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用EF 6中的自定义命名约定.我有2个表和一个联结表(WebUser,UserRequest,WebUserUserRequest).

I am experimenting with custom naming convenctions in EF 6. I have 2 tables and one junction table (WebUser, UserRequest, WebUserUserRequest).

我已经编写了应该能够重命名表的功能:从WebUser到web_user

I have written function that should be able to rename tables: from WebUser to web_user

private string GetTableName(Type type)
{
    var result = Regex.Replace(type.Name, ".[A-Z]", m => m.Value[0] + "_" + m.Value[1]);
    return result.ToLower();
}

以这种方式应用:

        modelBuilder.Types()
            .Configure(c => c.ToTable(GetTableName(c.ClrType)));

该功能在除联结表以外的所有表上都可以正常工作.

The function is working fine on all tables except junction tables.

源模型:

WebUser,UserRequest

WebUser, UserRequest

生成的数据库表:

web_user,user_request,WebUserUserRequest(而不是web_user_user_request)

web_user, user_request, WebUserUserRequest (instead of web_user_user_request)

是否可以这样设置结点命名约定?有没有办法配置命名对流以如上所述处理所有联结表(全部替换为大写并添加"_")?

Is it possible to set junction naming convenction this way? Is there a way how to configure naming convection to process all the junction tables as described above (replace all uppercase and add "_")?

推荐答案

可以通过这种方式添加一个约定,该约定设置与Entity Framework 6.1中包含的Public Mapping API的关联.IStoreModelConvention接口以类似的方式:

It is possible to add a convention this way that sets the associations with the Public Mapping API that was included in Entity Framework 6.1 To do that you have to implement the IStoreModelConvention interface in a similar way:

public class JunctionTableConvention : IStoreModelConvention<AssociationType>
{
    public void Apply(AssociationType item, DbModel model)
    {
        var associations = model.ConceptualToStoreMapping.AssociationSetMappings;

        foreach (var association in associations)
        {
            var associationSetEnds = association.AssociationSet.AssociationSetEnds;
            association.StoreEntitySet.Table = String.Format("{0}_{1}",
                GetTableName(associationSetEnds[0].EntitySet.ElementType),
                GetTableName(associationSetEnds[1].EntitySet.ElementType));
        }
    }

    private string GetTableName(EntityType type)
    {
        var result = Regex.Replace(type.Name, ".[A-Z]", m => m.Value[0] + "_" + m.Value[1]);
        return result.ToLower();
    }
}

只需将其添加到Conventions集合中,就必须将其包含在DbContext实现的OnModelCreating函数中:

And you have to include it in the OnModelCreating function of your DbContext implementation simply by adding it to the Conventions collection:

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

这篇关于EF 6,代码第一个联结表名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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