2017-12-06 5 views
-1

Ich muss die verwandte Navigationseigenschaft einer FK-Eigenschaft finden.Entity Framework: Ähnliche Navigationseigenschaft von FK-Eigenschaft finden

Das ist mein Modell ist:

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

Jetzt will ich etwas schreiben: erste

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

Ich verwende EF 6.2 mit Code.

Vielen Dank für jede Hilfe!

Antwort

0

Nach vielen Recherchen fand ich nicht ant Ressource oder Beispiel, wie es geht, aber ich fand eine temporäre Lösung mit dem folgenden Code, ich weiß nicht, ob es der optimale Weg ist oder es Ausnahmen gibt damit.

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

Wenn jemand eine bessere Lösung haben, wäre ich dankbar.

Verwandte Themen