EF4仅代码CTP中的关系映射(使用继承时?)

时间:2010-08-05 02:37:54

标签: entity-framework mapping code-first

我正在使用EF4 w /代码优先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();
    }

但我一定是错的,因为现在我明白了:

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

使用流畅API的各种其他方式产生不同的错误,但没有成功,所以我开始怀疑在使用继承时是否需要以不同的方式完成这些。

非常欢迎任何线索,链接,想法和指导。

1 个答案:

答案 0 :(得分:0)

使用MapHierarchy为我工作:

protected override void OnModelCreating(ModelBuilder builder){
    builder.Entity<CacheBlob>().HasKey(b=> b.Hash).MapHierarchy(); 
}

作为一个例子。

进一步参考:http://blogs.msdn.com/b/efdesign/archive/2009/10/12/code-only-further-enhancements.aspx

相关问题