我试图将我的类映射到现有数据库,但在部分外键声明中失败。实际上,我不想拥有字段外键,而只想拥有导航属性。这里是模型:
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????