【问题标题】:Getting foreign key from RelationshipEndMembers in EF6从 EF6 中的 RelationshipEndMembers 获取外键
【发布时间】:2015-08-05 00:20:53
【问题描述】:

我正在尝试使用一些 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";
            <#

【问题讨论】:

    标签: c# entity-framework entity-relationship t4


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多