Skip to content

Instantly share code, notes, and snippets.

@jennings
Last active December 2, 2021 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jennings/9aafcf0828a58a539117306b522a1b98 to your computer and use it in GitHub Desktop.
Save jennings/9aafcf0828a58a539117306b522a1b98 to your computer and use it in GitHub Desktop.
ForeignKey and InverseProperty placements for Entity Framework Core
public class Person
{
public int Id { get; set; }
public List<Book> AuthoredBooks { get; set; }
public List<Book> EditedBooks { get; set; }
}
public class Book
{
public int Id { get; set; }
public int AuthorId { get; set; }
public int EditorId { get; set; }
[ForeignKey("AuthorId")]
public Person Author { get; set; }
[ForeignKey("EditorId")]
public Person Editor { get; set; }
}
public class Person
{
public int Id { get; set; }
public List<Book> AuthoredBooks { get; set; }
public List<Book> EditedBooks { get; set; }
}
public class Book
{
public int Id { get; set; }
[ForeignKey("Author")]
public int AuthorId { get; set; }
[ForeignKey("Author")]
public int EditorId { get; set; }
public Person Author { get; set; }
public Person Editor { get; set; }
}
public class Person
{
public int Id { get; set; }
[ForeignKey("AuthorId")]
public List<Book> AuthoredBooks { get; set; }
[ForeignKey("EditorId")]
public List<Book> EditedBooks { get; set; }
}
public class Book
{
public int Id { get; set; }
public int AuthorId { get; set; }
public int EditorId { get; set; }
public Person Author { get; set; }
public Person Editor { get; set; }
}
public class Book
{
public int Id { get; set; }
public string ISBN { get; set; }
public List<ProductListing> Listings { get; set; }
}
public class ProductListing
{
public int Id { get; set; }
public string BookISBN { get; set; }
[ForeignKey("BookISBN")]
public Book Book { get; set; }
}
public class BookstoreContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<ProductListing>()
.HasOne(l => l.Book)
.WithMany(b => b.Listings)
.HasPrincipalKey(b => b.ISBN)
}
}
public class Person
{
public int Id { get; set; }
[InverseProperty("Author")]
public List<Book> AuthoredBooks { get; set; }
[InverseProperty("Editor")]
public List<Book> EditedBooks { get; set; }
}
public class Book
{
public int Id { get; set; }
public int AuthorId { get; set; }
public int EditorId { get; set; }
public Person Author { get; set; }
public Person Editor { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment