【发布时间】:2011-08-15 12:18:44
【问题描述】:
当两个表之间存在链接(连接)表时,我有一个关于一对多关系的问题。
示例表:
ChildTable:
ID int NOT NULL PK
Relation int NOT NULL
ParentTable:
ID int NOT NULL PK
Name nvarchar(50) NOT NULL
ParentChildren:
ParentTable_ID int NOT NULL PFK
ChildTable_ID int NOT NULL PFK
实体:
public class ChildTable
{
public ChildTable()
{
this.ParentTables = new List<ParentTable>();
}
public int ID { get; set; }
public int Relation { get; set; }
public virtual ICollection<ParentTable> ParentTables { get; set; }
}
public class ParentTable
{
public ParentTable()
{
this.ChildTables = new List<ChildTable>();
}
public int ID { get; set; }
public string Name { get; set; }
public virtual ICollection<ChildTable> ChildTables { get; set; }
}
映射:
public class ChildTableMap : EntityTypeConfiguration<ChildTable>
{
public ChildTableMap()
{
// Primary Key
this.HasKey(t => t.ID);
// Properties
// Table & Column Mappings
this.ToTable("ChildTable");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.Relation).HasColumnName("Relation");
}
}
public class ParentTableMap : EntityTypeConfiguration<ParentTable>
{
public ParentTableMap()
{
// Primary Key
this.HasKey(t => t.ID);
// Properties
this.Property(t => t.Name)
.IsRequired()
.HasMaxLength(50);
// Table & Column Mappings
this.ToTable("ParentTable");
this.Property(t => t.ID).HasColumnName("ID");
this.Property(t => t.Name).HasColumnName("Name");
// Relationships
this.HasMany(t => t.ChildTables)
.WithMany(t => t.ParentTables)
.Map(m =>
{
m.ToTable("ParentChildren");
m.MapLeftKey("ParentTable_ID");
m.MapRightKey("ChildTable_ID");
});
}
}
上下文:
public class TestContext : DbContext
{
static TestContext()
{
Database.SetInitializer<TestContext>(null);
}
public DbSet<ChildTable> ChildTables { get; set; }
public DbSet<ParentTable> ParentTables { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
modelBuilder.Configurations.Add(new ChildTableMap());
modelBuilder.Configurations.Add(new ParentTableMap());
}
}
添加孩子和父母的代码:
using (var context = new TestContext())
{
var parent = new ParentTable { Name = "Mother Goose" };
var child = new ChildTable { Relation = 1 };
context.ParentTables.Add(parent);
context.ChildTables.Add(child);
parent.ChildTables.Add(child);
context.SaveChanges();
}
一切都按预期工作,但我真的只有一位父母和许多孩子。
如何进行包括写入链接表的映射(更改了没有 ParentTable 的 ICollection 的 ChildTable 类)?
【问题讨论】:
-
你有这个现有的表结构并且不能改变它吗?我想知道,因为对于一对多的关系,您通常可以删除连接表并在 ChildTable 中引入一个 FK 列。我猜你不能因为某种原因改变你的桌子,对吧?
-
是的,没有那个链接表会很容易,但不幸的是,这个链接表不能更改。
标签: entity-framework-4.1 ef-code-first code-first