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.
BlogId
to post...?