与EF4 Code First相同的表如何做到很多 [英] how to do many to many with the same table with EF4 Code First
本文介绍了与EF4 Code First相同的表如何做到很多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个架构:
create table Person
(
id int identity primary key,
name nvarchar(30)
)
create table PersonPersons
(
PersonId references Person(id),
ChildPersonId references Person(id)
)
如何使用EF4创建类映射他们的代码第一个CTP5? / p>
how to create the classes to map them using EF4 Code First CTP5 ?
推荐答案
对于POCO ...
For the POCO...
class Person
{
public Guid PersonId { get; set; }
public virtual Person Parent { get; set; }
public virtual ICollection<Person> Children { get; set; }
}
...在DbContext ...中设置映射...
...set up the mapping in the DbContext...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Person>()
.HasOptional(entity => entity.Parent)
.WithMany(parent => parent.Children)
.HasForeignKey(parent => parent.PersonId);
}
...将给你一个默认的实现。如果您需要明确重命名表(并且需要多对多关系),请添加这样的内容...
...will give you a default implementation. If you need to rename the table explicitly (and want a many-to-many relationship), add in something like this...
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");
});
}
这篇关于与EF4 Code First相同的表如何做到很多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文