2

Is there a way to have navigation properties to Unique keys in EF Core? I tried "pretending" the unique key was a foreign key in the fluent api, but I got a runtime error (see comment).

I know EF Core has Alternate Keys, but I'm not sure if alternate keys can be used for navigation properties?

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        //runtime error: Method not found: 'Blog Post.get_Blog()'.
        modelBuilder.Entity<Post>()
            .HasOne(p => p.Blog)
            .WithMany(b => b.Posts)
            .HasForeignKey(p => p.BlogUrl)
            .HasPrincipalKey(b => b.Url);
    }
}

public class Blog
{
    public int BlogId { get; set; } //PK for Blog
    public string Url { get; set; } //Unique Key 

    public List<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; } //PK for Post
    public string Title { get; set; }
    public string Content { get; set; }

    public string BlogUrl { get; set; }
    public Blog Blog { get; set; }
}

Note: I did scaffold my database, and the scafoling did not produce navigation properties. Post.BlogUrl is NOT a ForeignKey to Blog.Url. However, Blog.Url is Unique.

6
  • Why aren't you adding BlogId to post...? Oct 12, 2016 at 22:01
  • @gdoron I'm working on an old application, and, if possible, I don't want to change the database. I want to see if there is a solution with fluent api first. Oct 12, 2016 at 22:05
  • Well seems like your code is 100% equal to their example doc. So if it doesn't work, you should open a ticket for them on GitHub. They usually respond quite quickly. Which version do you use BTW? Oct 12, 2016 at 22:07
  • Sorry for asking, but did you scaffold a migration first? Oct 12, 2016 at 22:16
  • @gdoron version of entity? I'm using Entity Core 1.0. Yeah I scaffolded and it didn't place navigation properties. I'm not surprised though because how would it know? Post.BlogUrl is not a ForeignKey to Blog.Url. It's just Blog.Url is unique. Oct 12, 2016 at 22:18

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy