Tuesday, January 1, 2013

Entity Framework One-to-One Relationship Association

In this scenario, Author has many books (1 to m). And the Author has the latest Book (1:1) as well.

Using the link as a reference, here is how I come up with the model and association.

Model:

public class Author
    {
        public int AuthorId { get; set; }
        public string Name { get; set; }
        public int LatestBookId { get; set; }
        public Book LatestBook { get; set; }
        public List<Book> Books { get; set; }
    }
    public class Book
    {
        public int BookId { get; set; }
        public string BookName { get; set; }
        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }

DbContext to set up the relationship using Fluent API

    public class EntityMappingContext : DbContext
    {
        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Author>()
                        .HasRequired(a => a.LatestBook)
                        .WithMany()
                        .HasForeignKey(u => u.LatestBookId);
            modelBuilder.Entity<Book>()
                        .HasRequired(a => a.Author)
                        .WithMany()
                        .HasForeignKey(u => u.AuthorId).WillCascadeOnDelete(false);
        }
    }




No comments: