C# 实体框架中抽象集合的映射关系

C# 实体框架中抽象集合的映射关系,c#,entity-framework,orm,ef-code-first,C#,Entity Framework,Orm,Ef Code First,我有两个类,每个类实现一个接口。其中一个类包含另一个类接口的ICollection 现在我想使用EF将其映射到我的数据库,但下面有一个异常。这有可能吗 我的类产品和类别的实体定义: public interface IProduct { string ProductId { get; set; } string CategoryId { get; set; } } public interface ICategory { string CategoryId { get;

我有两个类,每个类实现一个接口。其中一个类包含另一个类接口的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; }
}
我得到的例外情况如下。我是否应该以某种方式指定用于IPProduct的具体类型为ProductImpl


在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
{
}
    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.
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
{
}