【问题标题】:Many to many mapping not creating correct tables多对多映射未创建正确的表
【发布时间】:2012-08-30 20:48:01
【问题描述】:

我有一个模板

public class Template
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
    public virtual Template RelatedTemplate { get; set; }
    public virtual Field RelatedTemplatePrimaryField { get; set; }
    public virtual ICollection<Field> Fields { get; set; }
}

还有一个Field

public class Field
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Min { get; set; }
    public int Max { get; set; }
    public bool AllowEmpty { get; set; }
    public bool IsCollection { get; set; }
    public virtual ICollection<Template> Templates { get; set; }
}

问题是它没有创建多对多关系,它只是在字段表上添加了一个 FK,我想要一个多对多关系

Fields ICollection<Field> Fields

ICollection<Template> Templates

编辑: 如果我删除

public virtual Template RelatedTemplate { get; set; }
public virtual Field RelatedTemplatePrimaryField { get; set; }

它有效...有什么想法吗?

【问题讨论】:

    标签: c# .net ef-code-first entity-framework-5


    【解决方案1】:

    在这种情况下,您必须帮助 EF 正确识别您的关系。您可以通过数据注释来做到这一点:

    [InverseProperty("Fields")]
    public virtual ICollection<Template> Templates { get; set; }
    

    或通过 fluent-API:

    modelBuilder.Entity<Template>()
                .HasMany(t => t.Fields)
                .WithMany(f => f.Templates);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 2019-12-02
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多