0

If I defined one-to-many relation foreign-key constraints in Sql Server, Is it possible just define and use it in code-first class definitions in one side? For example suppose I have Library and Book classes. Each Library can has many books but each book belong to one library.

public class Book
    {
        public Book() { }

        public int BookId { get; set; }
        public string BookName { get; set; }

        public virtual Library Library { get; set; }
    }

public class Library
    {
        public Library() { }
        public int LibraryId { get; set; }

        public virtual ICollection<Book> Books { get; set; }
    }

If I want always just use this relation from Book side,Can I don't define below line in Library class definition?

public virtual ICollection<Book> Books { get; set; }
Mohammad Eslami
  • 536
  • 1
  • 6
  • 17

1 Answers1

0

Sure, you can do this:

modelBuilder.Entity<Book>()
            .HasRequired(b => b.Library) // Or: HasOptional
            .WithMany()
            .Map(m => m.MapKey("LibraryId"))

In this case, the database table Book has foreign key field LibraryId that's either required or optional (nullable). The foreign key is not mapped to a property in class Book. This is called an independent association.

You can also map the key to a property in Book if you want:

modelBuilder.Entity<Book>()
            .HasRequired(b => b.Library)
            .WithMany()
            .HasForeignKey(b => b.LibraryId))

This turns the association into a foreign key association. In many cases this can be beneficial.

Community
  • 1
  • 1
Gert Arnold
  • 105,341
  • 31
  • 202
  • 291