【问题标题】:Entity Framework: Find related navigation property by FK propertyEntity Framework:通过FK属性查找相关导航属性
【发布时间】:2017-12-06 07:14:16
【问题描述】:

我需要找到一个 FK 属性的相关导航属性。

这是我的模型:

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }

    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }
}

现在,我想写这样的东西:

var context = new BloggingContext();
var navigationProperty = GetNavigationProperty(context, typeof(Post), "BlogId"); // returns "Blog"

我首先使用带有代码的 EF 6.2。

感谢您的帮助!

【问题讨论】:

    标签: c# entity-framework ef-code-first


    【解决方案1】:

    经过大量研究,我没有找到ant资源或示例如何做到这一点,但我找到了一个临时解决方案,代码如下,我不知道这是最佳方式还是有异常它。

    public static string GetNavigationByForeignKey(this DbContext context, Type entityType, string fkPropertyName)
    {
        var objectContext = (context as IObjectContextAdapter).ObjectContext;
    
        var entityMetadata = objectContext.MetadataWorkspace
            .GetItems<EntityType>(DataSpace.CSpace)
            .FirstOrDefault(et => et.Name == entityType.Name);
    
        var navigationProperty = entityMetadata.NavigationProperties
            .FirstOrDefault(prop => prop.GetDependentProperties().Any(dep => dep.Name == fkPropertyName));
    
        return navigationProperty.Name;
    }
    

    如果有人有更好的解决方案,我将不胜感激。

    【讨论】:

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