我正在尝试使用实体框架中的代码优先设置,但遇到了困难。为了描述我想要完成的内容:
有一个名为Product的实体。该产品可以选择性地具有一个或多个相关的“子”产品。一个产品可以是一个或多个父产品的子级。
当我尝试生成与模型类“Product”绑定的控制器时,我收到一个错误消息:(更新,更加具体,与下面的代码匹配)
有一个名为Product的实体。该产品可以选择性地具有一个或多个相关的“子”产品。一个产品可以是一个或多个父产品的子级。
当我尝试生成与模型类“Product”绑定的控制器时,我收到一个错误消息:(更新,更加具体,与下面的代码匹配)
There was an error running the selected code generator:
'Unable to retrieve metadata for 'ProductCatalog.Models.Product'.
Multiple object sets per type are not supported. The object sets
'Product' and 'Products' can both contain instances of type
'ProductCatalog.Models.Product'.
以下是不起作用的模型类:
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace ProductCatalog.Models
{
// Product
public class Product
{
[Key]
public int ProductId { get; set; } // ProductID (Primary key)
public string ProductName { get; set; } // ProductName
public string ProductSku { get; set; } // ProductSKU
public int BaseQuantity { get; set; } // BaseQuantity
public decimal BaseCost { get; set; } // BaseCost
// Reverse navigation
public virtual ICollection<RelatedProduct> ParentProducts { get; set; } // RelatedProduct.FK_RelatedProductChildID
public virtual ICollection<RelatedProduct> ChildProducts { get; set; } // RelatedProduct.FK_RelatedProductParentID
public virtual ICollection<RelatedProduct> RelatedProducts { get; set; }
}
// RelatedProduct
public class RelatedProduct
{
[Key, Column(Order = 0)]
public int ParentId { get; set; } // ParentID
[Key, Column(Order = 1)]
public int ChildId { get; set; } // ChildID
public int Quantity { get; set; } // Quantity
public bool Required { get; set; } // Required
public bool Locked { get; set; } // Locked
// Foreign keys
public virtual Product ParentProduct { get; set; } // FK_RelatedProductParentID
public virtual Product ChildProduct { get; set; } // FK_RelatedProductChildID
}
public class ProductDBContext : DbContext
{
public IDbSet<Product> Product { get; set; } // Product
public IDbSet<RelatedProduct> RelatedProduct { get; set; } // RelatedProduct
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<RelatedProduct>()
.HasRequired(a => a.ParentProduct)
.WithMany(b => b.ChildProducts)
.HasForeignKey(c => c.ParentId) // FK_RelatedProductParentID
.WillCascadeOnDelete(false);
modelBuilder.Entity<RelatedProduct>()
.HasRequired(a => a.ChildProduct)
.WithMany(b => b.ParentProducts)
.HasForeignKey(c => c.ChildId); // FK_RelatedProductChildID
}
}
}
DbSet
是私有的。尝试将它们改为public
。或者这只是一个复制粘贴错误吗? - SlaumaToTable
。通常,您会使用ToTable
的第二个参数来定义模式,例如ToTable("Product", "dbo")
。或者干脆删除"dbo."
(仅使用ToTable("Product")
),因为 "dbo" 是默认模式。但是,我无法想象这解释了奇怪的异常。 - SlaumaProduct
DbSet,本来想写的 :) 恭喜!(EF 异常通常不能很好地指向问题的根源...) - Slauma