クラスを既存のデータベースにマップしようとしましたが、外部キー宣言の一部で失敗しました。実際には、フィールド外部キーは持ちたくありませんが、ナビゲーション プロパティのみが必要です。モデルは次のとおりです。
public class Template : BaseNamedType
{
//One template may has multiple TemplateSection
public virtual ICollection<TemplateSection> TemplateSection { get; set; }
...........
}
//Custom mapping class. I have field Order, without it mapping is simple
public class TemplateSection : BaseType
{
public virtual int Order { get; set; }
//Here is one-to-many relation, this field is required
public virtual Template Template { get; set; }
//Here is one-to-many relation, this field is required
public virtual Section Section { get; set; }
}
public class Section : BaseNamedType
{
//One section may be referenced by multiple TemplateSection
public virtual ICollection<TemplateSection> SectionTemplates { get; set; }
...........
}
これが私のデータベース作成スクリプトです:
CREATE TABLE [templates]
(
[id] INT NOT NULL IDENTITY(1, 1),
[name] NVARCHAR(300) NOT NULL,
);
GO;
CREATE TABLE [sections_to_templates]
(
[section_id] INT NOT NULL, //FK to [sections]
[template_id] INT NOT NULL, //FK to [templates]
[order] INT NOT NULL DEFAULT(0)
);
GO
CREATE TABLE [sections]
(
[id] INT NOT NULL IDENTITY(1, 1),
[name] NVARCHAR(300) NOT NULL,
);
GO
そして、ここで私のモデルバインディングコードでは、それが正しいかどうかは絶対にわかりません:
modelBuilder.Entity<Template>()
.HasKey(t0 => t0.Id)
.Map(m => m.ToTable("templates"))
.Property(x => x.Id)
.HasColumnName("id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
modelBuilder.Entity<Template>()
.HasMany(t0 => t0.TemplateSection)
.WithRequired(t1 => t1.Template)
.Map(??????????????????)
modelBuilder.Entity<TemplateSection>()
.HasKey(t0 => t0.Id)
.Map(m => m.ToTable("sections_to_templates"))
.Property(x => x.Id)
.HasColumnName("id")
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)
.IsRequired();
modelBuilder.Entity<TemplateSection>()
.HasRequired(t0 => t0.Template)
.WithMany(t1 => t1.TemplateSection)
.Map(m => m.MapKey("template_id"));
modelBuilder.Entity<TemplateSection>()
.HasRequired(t0 => t0.Section)
.WithMany(t1 => t1.SectionTemplates)
.Map(m => m.MapKey("section_id"));
//How to describe Section class????