Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails has-many-through equivalent in ASP.NET MVC3

In .NET Entity Framework, what is the best way to have a (custom) join table with extra attributes (other than ids) and/or associate this join table with others via separate model? In Ruby on Rails we can have a model for the join table, like:

Item.rb (model)
:has_many => :buyers, :through=>:invoice
...

Buyers.rb (model)
:has_many => :items, :through=>:invoice
...

Invoice.rb (model)
:belongs_to :item
:belongs_to :buyer
....

Then we can use: Item.first.buyers, Buyers.first.items and Buyer.create(:items=>Item.create(:name=>'random')) etc. just like when we use automated join table without model (using has_and_belongs_to_many).

In Visual Studio 2010's "Add Association" dialog, if we select multiplicity as *(Many) there is no option to select a join table (with model). Is there a way to do it manually?

like image 759
vulcan raven Avatar asked Dec 16 '11 16:12

vulcan raven


1 Answers

Yes, you can get something pretty close. I'm not quite sure how to set this up in the designer since I only work with codefirst.

Here's an example:

Student -> StudentFloor <- Floor

public class Student
{
    public int Id { get; set; }
    // ... properties ...

    // Navigation property to your link table
    public virtual ICollection<StudentFloor> StudentFloors { get; set; }

    // If you wanted to have a property direct to the floors, just add this:
    public IEnumerable<Floor> Floors
    {
        get
        {
            return StudentFloors.Select(ft => ft.Floor);
        }
    }
}

The linking table:

public class StudentFloor
{
    #region Composite Keys

    // Be sure to set the column order and key attributes.
    // Convention will link them to the navigation properties
    // below.  The database table will be created with a
    // compound key.

    [Key, Column(Order = 0)]
    public int StudentId { get; set; }

    [Key, Column(Order = 1)]
    public int FloorId { get; set; }

    #endregion

    // Here's the custom data stored in the link table

    [Required, StringLength(30)]
    public string Room { get; set; }

    [Required]
    public DateTime Checkin { get; set; }

    // Navigation properties to the outer tables
    [Required]
    public virtual Student Student { get; set; }

    [Required]
    public virtual Floor Floor { get; set; }

}

Finally, the other side of the many-to-many:

public class Floor
{
    public int Id { get; set; }
    // ... Other properties.

    public virtual ICollection<StudentFloor> StudentFloors { get; set; }
}
like image 66
Leniency Avatar answered Oct 18 '22 08:10

Leniency