System.Data.SqlClient.SqlException:列名无效' Reference_Id'

时间:2016-06-29 16:05:26

标签: c# asp.net-mvc ef-code-first entity-framework-6

我有两个班级:

public class Product
{
   public Guid Id {get;set;}
   public IList<Reference> References {get;set;}
} 

public class Reference
{
   public Guid Id {get;set;}
}

两个表都有很多关系,我在上下文文件中添加了。

modelBuilder.Entity<Product>()
                    .HasMany<Reference>(p => p.References)
                    .WithMany()
                    .Map(pxar =>
                    {
                        pxar.MapLeftKey("Product_Id");
                        pxar.MapRightKey("Reference_Id");
                        pxar.ToTable("ProductsXReferences");
                    });

不确定如何解决问题。我检查了Web.Config中的数据库表和连接字符串,一切看起来都正确。

1 个答案:

答案 0 :(得分:0)

您缺少参考产品的集合。尝试:

public class Product
{
   public Guid Id {get;set;}
   public ICollection<Reference> References {get;set;}
} 

public class Reference
{
   public Guid Id {get;set;}
   public ICollection<Product> Products {get;set;}
}

modelBuilder.Entity<Product>()
            .HasMany(p => p.References)
            .WithMany(r => r.Products)
            .Map(pxar =>
            {
                pxar.MapLeftKey("Product_Id");
                pxar.MapRightKey("Reference_Id");
                pxar.ToTable("ProductsXReferences");
            });

https://msdn.microsoft.com/en-us/data/hh134698.aspx