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