【问题标题】:Relationship Mapping in EF4 code-only CTP (when using inheritance?)EF4 纯代码 CTP 中的关系映射(使用继承时?)
【发布时间】:2011-03-25 14:13:45
【问题描述】:

我正在使用带有代码优先 CTP 功能的 EF4 生成一个简单的复合模式实体模型:

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.

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

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

【问题讨论】:

    标签: entity-framework mapping code-first


    【解决方案1】:

    使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 2013-11-16
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      相关资源
      最近更新 更多