2010-08-05 62 views
0

我使用EF4瓦特/代碼優先CTP特徵產生一個簡單的複合構圖實體模型:關係映射代碼僅CTP(使用繼承何時?)

public abstract partial class CacheEntity 
{ 
    [Key]public string Hash { get; set; } 
    public string Creator { get; set; } 
    public int EntityType { get; set; } 
    public string Name { get; set; } 
    public string Predecessor { get; set; } 
    public DateTime DateTimeCreated { get; set; } 

    public virtual ICollection<CacheReference> References { get; set; } 
} 

public partial class CacheBlob : CacheEntity 
{ 
    public byte[] Content { get; set; } 
} 

public partial class CacheCollection : CacheEntity 
{ 
    public virtual ICollection<CacheEntity> Children { get; set; } 
} 

public class CacheReference 
{ 
    public string Hash { get; set; } 
    [Key]public string Reference { get; set; } 

    public virtual CacheEntity Entity { get; set; } 
} 

public class CacheEntities : DbContext 
{ 
    public DbSet<CacheEntity> Entities { get; set; } 
    public DbSet<CacheReference> References { get; set; } 
} 

在我拆出原始/集的派生類它的所有工作很好,但現在我得到這樣的:

Unable to determine the principal end of the 'Cache.DataAccess.CacheEntity_References' 
relationship. Multiple added entities may have the same primary key. 

我想,它可能已被越來越糊塗,所以我想我會拼出來明確地使用了流暢的界面,而不是DataAnnotation屬性。下面是我覺得正確定義的關係:

protected override void OnModelCreating(ModelBuilder modelBuilder) 
    { 
     modelBuilder.Entity<CacheEntity>().HasKey(ce => ce.Hash); 
     modelBuilder.Entity<CacheEntity>().HasOptional(ce => ce.References).WithMany(); 
     modelBuilder.Entity<CacheReference>().HasKey(ce => ce.Reference); 
     modelBuilder.Entity<CacheReference>().HasRequired(cr => cr.Entity).WithOptional(); 
    } 

但我一定是錯誤的,因爲現在我得到這樣的:使用流利的API產生不同的錯誤

Entities in 'CacheEntities.CacheReferenceSet' participate in the 
'CacheReference_Entity' relationship. 0 related 'Entity' were found. 1 'Entity' is expected. 

各種方式,但沒有成功,所以我開始懷疑,當我使用繼承時,這些是否需要以不同的方式完成。

任何線索,鏈接,想法,指導將非常受歡迎。

回答