从 EF6 中的 RelationshipEndMembers 获取外键

Getting foreign key from RelationshipEndMembers in EF6

我正在尝试使用一些 T4 模板自动执行一些 EF6 linq 查询。

我有一个主要的 table 应用程序,它有许多 1-* 和一对 - 关系。

我已经弄清楚如何获取外键 table 简单导航属性的 ID 值,但我在处理多对多关系时遇到问题。

这是我到目前为止能够弄清楚的代码。

var association = ((AssociationType)entity.RelationshipType);

        if (association.ReferentialConstraints.Count > 0)
        {
            var fromProperties = association.ReferentialConstraints[0].FromProperties;
            var toProperties = association.ReferentialConstraints[0].ToProperties;
        #>
        //query = query.Where(p => p.<#=toProperties[0].Name#> == idToFind);
        <#
        }
        else if (association.RelationshipEndMembers.Count > 0)
        {
            var test = (AssociationEndMember)entity.FromEndMember;
            // ????????
// Trying to create something like
// query = query.Where(p => p.ManyToManey.ForeignKeyId== idToFind)
// I'm able to find the ManyToMany value but not the foreign Key value
            #>
                var hellowordl = "True";
            <#

所以我最终浏览了 edmx 属性并搜索了表的主键

var allEdmx = typeMapper.GetItemsToGenerate<EntityType>(itemCollection);

// entity is just an entry in allEdmx    
    var association = ((AssociationType)entity.RelationshipType);

    if (association.ReferentialConstraints.Count > 0)
    {
        var fromProperties = association.ReferentialConstraints[0].FromProperties;
        var toProperties = association.ReferentialConstraints[0].ToProperties;
    #>
    //query = query.Where(p => p.<#=toProperties[0].Name#> == idToFind);
    <#
    }
    else if (association.RelationshipEndMembers.Count > 0)
    {


var getPriamryKey = allEdmx.FirstOrDefault(d => d.Name == entity.FromEndMember.Name);
            var simpleProperties = typeMapper.GetSimpleProperties(getPriamryKey);
            if (simpleProperties.Any())
            {
                var primaryKeys = typeMapper.GetPrimaryKeys(ef, simpleProperties);

                if (primaryKeys.Any() && primaryKeys.Count() == 1)
                {
#>
        //query = query.Where(p => p.<#=entity.Name#>.<#=codeStringGenerator.JustGetName(primaryKeys.FirstOrDefault())#> == idToFind);
        <#
                }
}


// Added this to the codeStringGenerator class
    public string JustGetName(EdmProperty edmProperty)
    {
        return string.Format(
            CultureInfo.InvariantCulture,
            "{0}",
            _code.Escape(edmProperty)
            );
}