사이에 링크 (조인) 테이블이있을 때 두 테이블간에 일대 다 관계에 대한 질문이 있습니다.Entity Framework 코드 첫 번째 일대 다 관계 매핑 (링크 테이블 포함)
예 테이블 :
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 열을 도입 할 수 있기 때문에 궁금합니다. 웬일인지 당신 테이블을 바꿀 수 없다고 생각해? – Slauma
예, 링크 테이블이 없으면 매우 쉽지만, 불행히도이 링크 테이블은 변경할 수 없습니다. – Minnie