【问题标题】:Mapping relationships to collections of abstractions in Entity Framework将关系映射到实体框架中的抽象集合
【发布时间】:2012-09-19 18:21:26
【问题描述】:

我有两个类,每个类都实现了一个接口。其中一个类包含另一个接口的 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 之间的关系,所以我在我的 DbContext 中使用以下 OnModelCreating 方法:

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.

【问题讨论】:

    标签: c# entity-framework orm ef-code-first


    【解决方案1】:

    使用 EF 中的接口无法做到这一点。必须为要映射的属性映射导航属性的类型。对于要映射的类型,它必须是具体类型。

    如果您需要不同类型的产品和类别,您可以为它们使用基类:

    public class ProductBase
    {
        public string ProductId { get; set; }
        public string CategoryId { get; set; }
    }
    
    public class CategoryBase
    {
        public string CategoryId { get; set; }
        public virtual ICollection<ProductBase> Products { get; set; }
    }
    
    public class DerivedProduct : ProductBase
    {
    }
    
    public class DerivedCategory : CategoryBase
    {
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 1970-01-01
      • 1970-01-01
      • 2017-09-20
      • 2013-01-17
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多