0

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

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????
4

1 回答 1

0

在我看来,你几乎完成了:

  • 去掉第二个映射块,这是多余的,因为关系已经被第四个映射块覆盖了。

  • 您可以删除IsRequired()映射,因为只能要求不可为空的属性。

  • 您可以删除HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity)映射,因为默认情况下整数键是数据库生成的标识。

  • 对于字符串属性Name,您可以添加:

    modelBuilder.Entity<Template>()
        .Property(x => x.Name)
        .HasColumnName("name")
        .HasMaxLength(300)
        .IsRequired();
    // the same for Section
    
  • 如何描述Section类??? ”:和你的第一个映射块完全一样。

于 2013-01-06T19:56:42.507 回答