问题描述
在.NET实体框架,什么是有一个(自定义)连接表有额外的属性(IDS相比其他)和/或副本通过单独的模型他人连接表的最佳方法?在Ruby on Rails的,我们可以有一个连接表的模型,如:
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
....
然后我们可以使用: Item.first.buyers
, Buyers.first.items
和 Buyer.create(:项目=> Item.create(:名称=>'随机'))
等就像当我们使用自动连接表不模型(使用has_and_belongs_to_many)。
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).
在Visual Studio 2010中的添加关联对话框中,如果我们选择的多样性为*(多)没有选项来选择一个连接表(与模型)。有没有办法做手工?
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?
推荐答案
是的,你可以得到的东西pretty接近。我不太知道如何在设计器设置此,因为我只用codefirst工作。
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.
下面是一个例子:
学生 - > StudentFloor< - 地板
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);
}
}
}
链接表:
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; }
}
这篇关于Rails有一对多,通过ASP.NET MVC3相当于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!