c# - 尝试将对象与 EntityFramework 关联时出现无效列名错误

标签 c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

Entity Framework 给我带来了一些麻烦。

这是我的表格:

产品

Products Table

相关产品

RelatedProducts Table

还有我的数据库上下文(无论如何,它的一部分)...

ApplicationContext.cs

public class ApplicationContext : DbContext
{
        public ApplicationContext() : base("DefaultConnection")
        {
        }

        public DbSet<Product> Products { get; set; }
        public DbSet<RelatedProduct> RelatedProducts { get; set; }
}

还有模型...

Product.cs

public class Product
{
    public int ID              { get; set; }
    public string Manufacturer { get; set; }
    public string Model        { get; set; }
    public string PartNumber   { get; set; }
    public int CategoryID      { get; set; }
    public string Description  { get; set; }
    public decimal Price { get; set; }

    public virtual ICollection<RelatedProduct> RelatedProducts { get; set; }
}

RelatedProduct.cs

public class RelatedProduct
{
    public int ID        { get; set; }
    public int OwnerID   { get; set; }
    public int ProductID { get; set; }

    public virtual Product Owner { get; set; }
    public virtual Product Product { get; set; }
}

我想做什么

像这样循环遍历相关产品列表:

<ul class="activity">
      @foreach (var related in @Model.RelatedProducts)
      {
             <li>
                  <i class="fa fa-chevron-right red"></i> <strong>@related.Product.Manufacturer:</strong> @related.Product.Model
             </li>
      }
</ul>

问题

我一直收到这个错误L

{"Invalid column name 'Product_ID'.\r\nInvalid column name 'Product_ID'.\r\nInvalid column name 'Product_ID'."}

有什么想法吗?

最佳答案

如果 Product.RelatedProductsRelatedProduct.OwnerRelatedProduct.Product 的反向导航属性,您必须告诉 EF。两者都是可能且有效的,EF 无法自行决定。

带有数据注释的解决方案(假设 OwnerRelatedProducts 的倒数):

[InverseProperty("RelatedProducts")]
public virtual Product Owner { get; set; }

public virtual Product Product { get; set; }

或使用 Fluent API:

modelBuilder.Entity<RelatedProduct>()
    .HasRequired(r => r.Owner)
    .WithMany(p => p.RelatedProducts)
    .HasForeignKey(r => r.OwnerID);

modelBuilder.Entity<RelatedProduct>()
    .HasRequired(r => r.Product)
    .WithMany()
    .HasForeignKey(r => r.ProductID)
    .WillCascadeOnDelete(false);

可能只有 Fluent API 解决方案可以工作,因为您还需要为其中一种关系禁用级联删除,而这对于数据注释是不可能的。

关于c# - 尝试将对象与 EntityFramework 关联时出现无效列名错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24454938/

相关文章:

c# - 通过公共(public)属性访问私有(private)变量

asp.net-mvc - 为什么Hangfire需要验证才能查看仪表板

asp.net - 在 MVC 3 + Entity Framework 中创建 WebForms 应用程序

c# - 两个 Ulong 整数相除输出错误的结果

c# - Paypal IPN 通知失败但未设置

c# - 如何从字符中添加字符

asp.net - 关闭请求验证在 MVC 页面上不起作用

asp.net - WebMatrix 中的异步页面?

asp.net - ASP.NET MVC 中请求的日期 header

C# - 我知道,我知道,关于 Dispose 的另一个问题(与设计更相关)!