EF7 - RC2上的列名无效

时间:2016-07-23 16:36:37

标签: sql-server asp.net-core-mvc entity-framework-core

我收到错误"列名无效"在实体框架RC 2上,下面是我的实体

public class Article : IEntityBase
    {       
       public Article()
        {
            TagMaps = new List<ArticleTagMap>();

        }
        public int Id { get; set; }

        [Required, MaxLength(100), MinLength(3)]
        public string Slug { get; set; }

        [Required]
        public string Title { get; set; }

        [Required]
        public string Description { get; set; }

        [MaxLength(255)]
        public string ShortDescription { get; set; }

        [MaxLength(255)]
        public string Metadata { get; set; }

        public virtual ICollection<ArticleTagMap> TagMaps { get; set; }

    }

public class Tag :IEntityBase 
    {
        public Tag()
        {
            TagMaps = new List<ArticleTagMap>();
        }

        public int Id { get; set; }

        [Required, MaxLength(100)]
        public string TagName { get; set; }

        public virtual ICollection<ArticleTagMap> TagMaps { get; set; }


    }

public class ArticleTagMap : IEntityBase
    {


        public int Id { get; set; }

        [Required]
        public int ArticleId { get; set; }
        [Required]
        public int TagId { get; set; }

        [ForeignKey("TagId")]
        public virtual Tag Tag { get; set; }

        [ForeignKey("ArticleId")]
        public virtual Article Article { get; set; }

    }

并在DataContext上添加以下代码

protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     modelBuilder.Entity<ArticleTagMap>()
                .HasOne(a => a.Tag)
                .WithMany(b => b.TagMaps)
                .HasForeignKey(c => c.TagId)
                .OnDelete(DeleteBehavior.Cascade);

            modelBuilder.Entity<ArticleTagMap>()
                .HasOne(a => a.Article)
                .WithMany(b => b.TagMaps)
                .HasForeignKey(c => c.ArticleId)
                .OnDelete(DeleteBehavior.Cascade);
 }

从SQL分析器我捕获生成的脚本

exec sp_executesql N'SELECT [a0].[Id], [a0].[ArticleId], [a0].[ArticleId1], [a0].[TagId], [a0].[TagId1]
FROM [ArticleTagMaps] AS [a0]
INNER JOIN (
    SELECT DISTINCT TOP(1) [a].[Id]
    FROM [Campaigns] AS [x]
    INNER JOIN [Articles] AS [x.Article] ON [x].[ArticleId] = [x.Article].[Id]
    INNER JOIN [Articles] AS [a] ON [x].[ArticleId] = [a].[Id]
    WHERE [x.Article].[Slug] = @__slug_0
    ORDER BY [a].[Id]
) AS [a1] ON [a0].[ArticleId1] = [a1].[Id]
ORDER BY [a1].[Id]',N'@__slug_0 nvarchar(4000)',@__slug_0=N'bantu-pekak-sanin'

表中没有ArticleId1和TagId1列名。我已经挣扎了好几个小时,仍然找不到任何解决方案。请帮助:)

1 个答案:

答案 0 :(得分:-1)

1)尝试从.HasForeignKey()中删除OnModelCreating - 您已在[ForeignKey(...)]属性中拥有此信息(或从ArticleTagMap中删除此属性)并重新创建迁移脚本

2)您不需要在分析器中捕获SQL。您可以检查生成的迁移脚本(或整个模型的migrations/<DbContextName>DbModelSnapshot.cs文件),以确保EF“正确理解”您的模型