加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails在ASP.NET MVC3中具有多个等价物

发布时间:2020-12-16 23:34:57 所属栏目:百科 来源:网络整理
导读:在.NET实体框架中,具有额外属性(除了ids)和/或通过单独模型将此连接表与其他属性关联的(自定义)连接表的最佳方法是什么?在Ruby on Rails中,我们可以为连接表建立一个模型,例如: Item.rb (model):has_many = :buyers,:through=:invoice...Buyers.rb (model)
在.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
....

然后我们可以使用:Item.first.buyers,Buyers.first.items和Buyer.create(:items => Item.create(:name =>’random’))等,就像我们使用自动连接表一样没有模型(使用has_and_belongs_to_many).

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

解决方法

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

这是一个例子:

学生 – > StudentFloor< - 楼层

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

链接表:

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

}

最后,多对多的另一面:

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

    public virtual ICollection<StudentFloor> StudentFloors { get; set; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读