Wednesday, April 4, 2018

EF Core FK question

Hello all.

Been out of the C# game for about 5 years and back then most data interaction was ADO.NET and some Dapper. Starting to get back into things with .NET core and EF Core. Have a couple of questions:

public class Author { public int AuthorId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public ICollection<Book> Books { get; set; } } // Author to Book only. Creates a shadow FK. OnDelete is Restrict. public class Book { public int BookId { get; set; } public string Title { get; set; } } // Author to Book, Book to Author. Creates a shadow FK. OnDelete is Restrict. public class Book { public int BookId { get; set; } public string Title { get; set; } public Author Author { get; set; } } // Author to Book, Book to Author. Fully Defined Relationship. OnDelte is Cascade public class Book { public int BookId { get; set; } public string Title { get; set; } public int AuthorId { get; set; } public Author Author { get; set; } } 

Personally, I think having to define both Author and AuthorId to get the full relationship is a little ugly but you do what you gotta do.

Question 1: With EF Core's fluent api could I

modelBuilder.Entity<Author>() .HasMany(a => a.Books) .WithOne(b => b.Author) .OnDelete(DeleteBehavior.Cascade) 

and just use the 2nd version of Book?

If no, Question 2: With the third version of Book, Do you have to provide values for both Author and AuthorId before saving to the database? Or do you provide Author and EF core handles it for you?

Thanks in advance!

EF Core FK question Click here
  • Blogger Comment
  • Facebook Comment

0 comments:

Post a Comment

The webdev Team