Certainly! Here is the example for establishing a relationship between tables using Entity Framework Code First in English:
Let's start by installing the necessary NuGet packages for Entity Framework using the NuGet Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Now, let's proceed with an example. In this example, we will have two tables: Author
and Book
. An author can have multiple books, so we will establish a relationship between these two tables.
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
// Author model class
public class Author
{
public int AuthorId { get; set; }
public string Name { get; set; }
// Relationship for author's books
public virtual ICollection<Book> Books { get; set; }
}
// Book model class
public class Book
{
public int BookId { get; set; }
public string Title { get; set; }
// Relationship for book's author
public int AuthorId { get; set; }
public virtual Author Author { get; set; }
}
// Database context class
public class BookStoreContext : DbContext
{
public DbSet<Author> Authors { get; set; }
public DbSet<Book> Books { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("your_connection_string_here");
}
}
class Program
{
static void Main()
{
using (var context = new BookStoreContext())
{
// Ensure the database is created
context.Database.EnsureCreated();
// Add sample data
var author = new Author { Name = "John Doe" };
var book = new Book { Title = "Sample Book", Author = author };
context.Authors.Add(author);
context.Books.Add(book);
context.SaveChanges();
}
}
}
Explanation:
Author and Book Classes: The Author
and Book
classes are created. In the Author
class, the Books
property signifies that an author can have multiple books. In the Book
class, the Author
property indicates the relationship with the author.
BookStoreContext Class: This class manages database operations. The DbSet properties represent the tables to be created in the database.
OnConfiguring Method: This method sets the database connection settings. In this example, SQL Server is used, and a connection string is added.
Main Method: It is used to add sample data. An author and a book are created, and a relationship is established before saving them to the database.
In this example, a relationship is established between the "Author" and "Book" tables, indicating that an author can have multiple books.