我有這樣的模式:怎麼辦多對多與同桌EF4代碼優先
create table Person
(
id int identity primary key,
name nvarchar(30)
)
create table PersonPersons
(
PersonId references Person(id),
ChildPersonId references Person(id)
)
如何使用EF4代碼優先CTP5創建類映射呢?
我有這樣的模式:怎麼辦多對多與同桌EF4代碼優先
create table Person
(
id int identity primary key,
name nvarchar(30)
)
create table PersonPersons
(
PersonId references Person(id),
ChildPersonId references Person(id)
)
如何使用EF4代碼優先CTP5創建類映射呢?
對於POCO ...
class Person
{
public Guid PersonId { get; set; }
public virtual Person Parent { get; set; }
public virtual ICollection<Person> Children { get; set; }
}
......設立在的DbContext的映射......
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasOptional(entity => entity.Parent)
.WithMany(parent => parent.Children)
.HasForeignKey(parent => parent.PersonId);
}
...會給你一個默認的實現。如果您需要重命名明確表(並希望多到許多關係),加入這樣的事情...
class Person
{
public Guid PersonId { get; set; }
public virtual ICollection<Person> Parent { get; set; }
public virtual ICollection<Person> Children { get; set; }
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
ConfigureProducts(modelBuilder);
ConfigureMembership(modelBuilder);
modelBuilder.Entity<Person>()
.HasMany(entity => entity.Children)
.WithMany(child => child.Parent)
.Map(map =>
{
map.ToTable("PersonPersons");
map.MapLeftKey(left => left.PersonId, "PersonId");
map.MapRightKey(right => right.PersonId, "ChildPersonId");
// For EF5, comment the two above lines and uncomment the two below lines.
// map.MapLeftKey("PersonId");
// map.MapRightKey("ChildPersonId");
});
}
[實體框架4 CTP 5自我
可能重複引用許多一對多](http://stackoverflow.com/questions/4981228/entity-framework-4-ctp-5-self-referencing-many-to-many) – 2011-02-24 10:04:22