我有这样的模式:怎么办多对多与同桌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