subseven
subseven

Reputation: 89

problem on one-to-many relationships entity framework 4.1 mvc

i have these models:

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public ICollection<Books> FavoriteBooks { get; set; }
}

public class Books
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author{ get; set; }
}

When i run DBContext and check the generated tables, the Books table have created Student_Id column. I want the Books table to be just a reference and not linked back to Student. How can I make this relationship uni-directional and will have no Student_Id column created in Books? can i use fluent-api? or in simple data annotations only?

thanks

Upvotes: 1

Views: 1446

Answers (1)

Matt Hamilton
Matt Hamilton

Reputation: 204229

In the fluent API it should look something like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
                .HasMany(s => s.FavoriteBooks)
                .WithMany();
}

That'll create a "StudentBooks" table for you to maintain the many-to-many relationship. It's not a one-to-many relationship as your question suggests, since a student can have many favourite books, but each book might be a favourite of many students.

Update

For the sake of completeness, here's how you'd do it if you already have that linking table defined and need to tell EF what the mapping looks like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
                .HasMany(s => s.FavoriteBooks)
                .WithMany();
                .Map(cfg => cfg.MapLeftKey("Student_Id")
                               .MapRightKey("Books_Id")
                               .ToTable("StudentBooks"));
}

Upvotes: 3

Related Questions