EF 6关系:在模型生成期间检测到一个或多个验证错误

时间:2016-10-10 12:34:35

标签: c# asp.net-mvc entity-framework asp.net-mvc-5 entity-relationship

我一直在拉我的头发试图找出我认为相对简单的关系映射(一对多)。

让我们回顾一下模特中的内容:

ContentExternalLink

public class ContentExternalLink
{
    public ContentExternalLink()
    {
        ContentTagAssignments = new List<ContentTagAssignment>();
    }

    [Key]
    public string LinkId { get; set; }
    public string LinkTypeId { get; set; }
    public string LinkTitle { get; set; }
    public string LinkUrl { get; set; }
    public string LinkSource { get; set; }
    public string LinkPhoneNumber { get; set; }
    public DateTime LinkDate { get; set; }
    public DateTime LinkCreatedDate { get; set; }
    public DateTime LinkModifiedDate { get; set; }
    [ScriptIgnore]
    public virtual ICollection<ContentTagAssignment> ContentTagAssignments { get; set; }
}

ContentTagAssignmnent

public class ContentTagAssignment
{
    public ContentTagAssignment()
    {
        this.ContentExternalLink = new ContentExternalLink();
    }

    [Key]
    public string TagId { get; set; }
    [Key]
    public string ArticleId { get; set; }
    public bool IsPrimary { get; set; }
    public DateTime CreatedDate { get; set; }
    [ScriptIgnore]
    public virtual ContentExternalLink ContentExternalLink { get; set; }
}

现在进入映射:

ContentExternalLinkMap

public class ContentExternalLinkMap : EntityTypeConfiguration<ContentExternalLink>
{
    public ContentExternalLinkMap()
    {
        this.ToTable("content_external_link", "dbo");

        this.HasKey(c => c.LinkId);

        this.Property(c => c.LinkId).HasColumnName("link_id");
        this.Property(c => c.LinkTypeId).HasColumnName("link_type_id");
        this.Property(c => c.LinkTitle).HasColumnName("link_title");
        this.Property(c => c.LinkUrl).HasColumnName("link_url");
        this.Property(c => c.LinkSource).HasColumnName("link_source");
        this.Property(c => c.LinkPhoneNumber).HasColumnName("link_phone_number");
        this.Property(c => c.LinkDate).HasColumnName("link_date");
        this.Property(c => c.LinkCreatedDate).HasColumnName("link_created_date");
        this.Property(c => c.LinkModifiedDate).HasColumnName("link_modified_date");
    }
}

ContentTagAssignmnetMap

public class ContentTagAssignmentMap : EntityTypeConfiguration<ContentTagAssignment>
{
    public ContentTagAssignmentMap()
    {
        this.ToTable("content_tag_assignment", "dbo");

        this.HasKey(t => new {t.TagId, t.ArticleId});

        this.Property(t => t.TagId).HasColumnName("tag_id");
        this.Property(t => t.ArticleId).HasColumnName("article_id");
        this.Property(t => t.IsPrimary).HasColumnName("is_primary_tag");
        this.Property(t => t.CreatedDate).HasColumnName("created_date");


        this.HasOptional(t => t.ContentExternalLink)
            .WithMany(t => t.ContentTagAssignments)
            .HasForeignKey(t => new {t.TagId, t.ArticleId});
    }
}

这种关系肯定是奇怪的,因为LinkId会与ContentTagAssignment中的ArticleId匹配。

我在ContentTagAssignmentMap中尝试了以下内容:

    //this.HasOptional(t => t.ContentExternalLink)
//    .WithMany(t => t.ContentTagAssignments)
//    .HasForeignKey(t => t.ContentExternalLink);

this.HasOptional(x => x.ContentExternalLink)
    .WithMany(x=>x.ContentTagAssignments)
    .Map(x => x.MapKey("LinkId").HasColumnAnnotation("LinkId","ArticleId",null));

//this.Map(m =>
//    {
//        m.Properties(x => x.ArticleId);
//        m.ToTable("content_tag_assignment");
//    })
//    .Map(p =>
//    {
//        p.Properties(x => x.ContentExternalLink.LinkId);
//        p.ToTable("ContentExternalLink");
//    });

评论的关系不起作用。有效的(因为它在初始页面加载时不会失败)。但是,当我尝试从ContentExternalLink访问列表时,出现以下错误:{&#34;列名称无效&#39; LinkId&#39;。\ r \ n无效的列名称&#39; LinkId&#39; &#34;}

所以我更失落......

问题

基本上,并非每个ContentExternalLink都会为其分配标记。但是,如果有ContentTternalAternal的ContentTagAssignments,我应该能够得到它们的列表。此外,TagId和ArticleId是字符串(guids)。

有人有任何建议吗?

谢谢!

3 个答案:

答案 0 :(得分:2)

ivan stoev的评论之后,我发现当外键也是主键(not nullable

时,这里的唯一错误是设置可选

所以映射将是:

public class ContentTagAssignmentMap : EntityTypeConfiguration<ContentTagAssignment>
{
    public ContentTagAssignmentMap()
    {
        this.ToTable("content_tag_assignment", "dbo");

        this.HasKey(t => new { t.TagId, t.ArticleId });

        this.Property(t => t.TagId).HasColumnName("tag_id");
        this.Property(t => t.ArticleId).HasColumnName("article_id");
        this.Property(t => t.IsPrimary).HasColumnName("is_primary_tag");
        this.Property(t => t.CreatedDate).HasColumnName("created_date");


        this.HasRequired(t => t.ContentExternalLink)
            .WithMany(t => t.ContentTagAssignments)
            .HasForeignKey(t => t.ArticleId)
            .WillCascadeOnDelete(false);
    }
}

以下是您的模型的工作示例:

class Program
{
    static void Main(string[] args)
    {
        var ctx = new Context();
        ctx.Database.Delete();
        ctx.Database.CreateIfNotExists();

        Console.ReadKey();
    }
}

public class Context : DbContext
{
    public Context():base ("Teste")
    {

    }

    public DbSet<ContentExternalLink> ContentExternalLinks { get; set; }
    public DbSet<ContentTagAssignment> ContentTagAssignments { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ContentExternalLinkMap());
        modelBuilder.Configurations.Add(new ContentTagAssignmentMap());

        base.OnModelCreating(modelBuilder);
    }

}

public class ContentExternalLink
{
    public ContentExternalLink()
    {
        ContentTagAssignments = new List<ContentTagAssignment>();
    }

    [Key]
    public string LinkId { get; set; }
    public string LinkTypeId { get; set; }
    public string LinkTitle { get; set; }
    public string LinkUrl { get; set; }
    public string LinkSource { get; set; }
    public string LinkPhoneNumber { get; set; }
    public DateTime LinkDate { get; set; }
    public DateTime LinkCreatedDate { get; set; }
    public DateTime LinkModifiedDate { get; set; }

    public virtual ICollection<ContentTagAssignment> ContentTagAssignments { get; set; }
}

public class ContentTagAssignment
{
    public ContentTagAssignment()
    {
        this.ContentExternalLink = new ContentExternalLink();
    }

    [Key]
    public string TagId { get; set; }
    [Key]
    public string ArticleId { get; set; }
    public bool IsPrimary { get; set; }
    public DateTime CreatedDate { get; set; }

    public virtual ContentExternalLink ContentExternalLink { get; set; }
}

public class ContentExternalLinkMap : EntityTypeConfiguration<ContentExternalLink>
{
    public ContentExternalLinkMap()
    {
        this.ToTable("content_external_link", "dbo");

        this.HasKey(c => c.LinkId);

        this.Property(c => c.LinkId).HasColumnName("link_id");
        this.Property(c => c.LinkTypeId).HasColumnName("link_type_id");
        this.Property(c => c.LinkTitle).HasColumnName("link_title");
        this.Property(c => c.LinkUrl).HasColumnName("link_url");
        this.Property(c => c.LinkSource).HasColumnName("link_source");
        this.Property(c => c.LinkPhoneNumber).HasColumnName("link_phone_number");
        this.Property(c => c.LinkDate).HasColumnName("link_date");
        this.Property(c => c.LinkCreatedDate).HasColumnName("link_created_date");
        this.Property(c => c.LinkModifiedDate).HasColumnName("link_modified_date");
    }
}

public class ContentTagAssignmentMap : EntityTypeConfiguration<ContentTagAssignment>
{
    public ContentTagAssignmentMap()
    {
        this.ToTable("content_tag_assignment", "dbo");

        this.HasKey(t => new { t.TagId, t.ArticleId });

        this.Property(t => t.TagId).HasColumnName("tag_id");
        this.Property(t => t.ArticleId).HasColumnName("article_id");
        this.Property(t => t.IsPrimary).HasColumnName("is_primary_tag");
        this.Property(t => t.CreatedDate).HasColumnName("created_date");


        this.HasRequired(t => t.ContentExternalLink)
            .WithMany(t => t.ContentTagAssignments)
            .HasForeignKey(t => t.ArticleId)
            .WillCascadeOnDelete(false);
    }
}

以下是上述代码的结果:

Created Tables

答案 1 :(得分:1)

您的实体模型/实施存在两个问题。

让我们从simlpler开始(在Gert Arnold's comment中提到)。根据经验,您不应该在构造函数(或内部任何其他位置)内初始化单个导航属性,因为这会破坏EF延迟加载行为。

很快,只需删除

this.ContentExternalLink = new ContentExternalLink();

来自ContentTagAssignment类构造函数的行。

现在主要问题。 EF6仅支持引用主端的PK(主键)的FK(外键)关系。这意味着您无法在TagId, ArticleId实体中使用复合键(ContentTagAssignment)来引用LinkId实体的单个PK(ContentExternalLink),因为您尝试设置通过HasForeignKey(t => new {t.TagId, t.ArticleId})电话。这两列构成从属端(ContentTagAssignment)的PK的事实与关系无关。没有其他选择 - 您必须从两个字段中选择一个。根据 LinkId将与ContentTagAssignment 中的ArticleId匹配,这应该是ArticleId字段。

如果我的猜测是正确的,只需替换

this.HasOptional(t => t.ContentExternalLink)
    .WithMany(t => t.ContentTagAssignments)
    .HasForeignKey(t => new {t.TagId, t.ArticleId});

this.HasRequired(t => t.ContentExternalLink)
    .WithMany(t => t.ContentTagAssignments)
    .HasForeignKey(t => t.ArticleId);

并且(连同构造函数修改)应该解决问题。

请注意,我还将HasOptional更改为HasRequired,因为ArticleId字段是PK的一部分,因此无论如何都不会允许null值。

答案 2 :(得分:0)

我认为问题在于您尝试使用外键而未指示正确的连接。

您需要做的是将一个LinkId字段添加到ContentTagAssignment,这是您应该使用的实际外键并加入到该字段:

this.HasOptional(t => t.ContentExternalLink)
.WithMany(t => t.ContentTagAssignments)
.HasForeignKey(t => t.LinkId);

原因是你要告诉它找一个ContentExternalLink中不存在的密钥(tagId,ArticleId)。