实体框架:通过FK属性查找相关的导航属性

时间:2017-12-06 07:14:17

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

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

这是我的模特:

import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { AngularFireDatabase } from 'angularfire2/database';
constructor(
private afs: AngularFirestore,
private angularfire: AngularFireDatabase
) { }convert() {
this.itemsCollection = this.afs.collection('requests'); //ref()
this.angularfire.list('/requests/').auditTrail().subscribe((data: any) => {
  _.each(data, element => {
    this.itemsCollection.doc(element.key).set(element.payload.val())
      .then((result) => {
      });
  });
});}

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

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; }
}

我首先使用EF 6.2代码。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

经过大量的研究,我没有找到蚂蚁资源或示例如何做,但我找到了一个临时解决方案,使用以下代码,我不知道这是最佳方式还是有例外。

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;
}

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

相关问题