在EF6中从RelationshipEndMembers获取外键

本文关键字:获取 RelationshipEndMembers EF6 中从 | 更新日期: 2023-09-27 18:06:21

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

我有一个名为Application的主表,它有许多1-*和一对-关系。

我已经能够弄清楚如何获得简单导航属性的外键表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";
            <#

在EF6中从RelationshipEndMembers获取外键

所以我最终遍历了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)
            );
}