Rails在ASP.NET MVC3中具有多个等价物

vul*_*ven 8 orm many-to-many model ruby-on-rails asp.net-mvc-3

在.NET实体框架中,有一个(自定义)连接表具有额外属性(除了ids)和/或通过单独的模型将此连接表与其他人联系起来的最佳方法是什么?在Ruby on Rails中,我们可以为连接表建立一个模型,例如:

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
....
Run Code Online (Sandbox Code Playgroud)

然后我们可以使用:Item.first.buyers,Buyers.first.items并且Buyer.create(:items=>Item.create(:name=>'random'))当我们使用自动连接表无模型(使用has_and_belongs_to_many)等只是喜欢.

在Visual Studio 2010的"添加关联"对话框中,如果我们选择多重性为*(多个),则无法选择连接表(带有模型).有没有办法手动完成?

Len*_*ncy 6

是的,你可以得到非常接近的东西.我不太确定如何在设计器中设置它,因为我只使用codefirst.

这是一个例子:

学生 - >学生楼层< - 楼层

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

链接表:

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; }

}
Run Code Online (Sandbox Code Playgroud)

最后,多对多的另一面:

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

    public virtual ICollection<StudentFloor> StudentFloors { get; set; }
}
Run Code Online (Sandbox Code Playgroud)