2012-09-19 36 views
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. 

回答

0

用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 
{ 
}