1
我有兩個類,每個實現一個接口。其中一個類包含另一個接口的ICollection。將關係映射到實體框架中的抽象集合
現在我想用EF映射到我的數據庫,但得到一個異常(下面)。這應該是可能的嗎?
我類(產品和類別)實體的定義:
public interface IProduct
{
string ProductId { get; set; }
string CategoryId { get; set; }
}
public interface ICategory
{
string CategoryId { get; set; }
ICollection<IProduct> Products { get; set; };
}
public class ProductImpl : IProduct
{
public string ProductId { get; set; }
public string CategoryId { get; set; }
}
public class CategoryImpl : ICategory
{
public string CategoryId { get; set; }
public ICollection<IProduct> Products { get; set; }
}
我要地圖CategoryImpl和ProductImpl之間的關係,所以我用下面的方法OnModelCreating
在我的DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var a = modelBuilder.Entity<CategoryImpl>();
a.ToTable("Categories");
a.HasKey(k => k.CategoryId);
a.Property(p => p.CategoryId);
a.HasMany(p => p.Products).WithOptional().HasForeignKey(p => p.CategoryId);
var b = modelBuilder.Entity<ProductImpl>();
b.ToTable("Products");
b.HasKey(k => k.ProductId);
b.Property(p => p.ProductId);
}
我得到的例外如下。我應該以某種方式指定IProduct
使用的具體類型是ProductImpl
?
System.InvalidOperationException: The navigation property 'Products'
is not a declared property on type 'CategoryImpl'. Verify that it has
not been explicitly excluded from the model and that it is a valid navigation property.