在Entity Framework 4.1中使用外键的抽象属性?

时间:2012-02-02 14:08:22

标签: entity-framework entity-framework-4

更新: 我更新了类,看起来更像我的实际模型。当我从Document基础实体中删除Assignable属性时,一切正常。

这样的东西可以在EF 4.1中映射吗?

public abstract class Entity
{
   public Guid Id {get;set;}
}    

public abstract class Assignable:Entity
    {

    }

    public class Contact: Assignable
    {
         public string Name {get;set;}
    }

    public class Partner: Assignable
    {
         public string Area {get;set;}
    }

    public abstract class Document: Entity        {

         public Guid AssignedToId {get;set}
         public Assignable AssignedTo {get;set;
    }

    public class Submittal: Document
    {
         public string SomeProperty {get;set;}
    }

映射:

    public class EntityConfiguration<TEntity> : EntityTypeConfiguration<TEntity>
        where TEntity : Entity
        {
            protected EntityConfiguration()
            {
                HasKey(e => e.Id);
                Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

            }
        }

    public class AssignableEntityMapping<TEntity>: EntityConfiguration<TEntity> where TEntity: Assignable
{

}
    public class DocumentEntityMapping<TEntity>: EntityConfiguration<TEntity>
        {
            public DocumentEntityMapping()
            {

                HasOptional(e => e.AssignedTo).WithMany().HasForeignKey(e => e.AssignedToId);
            } 
        }

public class ContactMapping: AssignableEntityMapping<Contact>
{
....
}

public class PartnerMapping: AssignableEntityMapping<Partner>
{
....
}

public class SubmittalMapping: DocumentEntityMapping<Submittal>
{
....
}

如果可以,我该如何设置映射,以便AssignedToId是其中一个具体实体的外键?我为Document实体创建了一个映射,我得到了错误:“属性'Id'不是类型的声明属性...”我猜这是因为EF不知道如何区分AssignedToId引用的内容?

1 个答案:

答案 0 :(得分:0)

我在ContactPartner实体周围有很多额外的架构,我无法使用TPH (Table Per Hierarchy)方法。由于我试图同时使用Table per Concrete Type (TPC),因此EF不知道如何在Document类中映射AssignedToId。我最后只是将所有“可赋值”类型添加到Document类中。如果有另一种方式,我想知道。

public abstract class Document: Entity
{
     public Guid? AssignedContactId {get;set;}
     public Contact AssignedContact {get;set;}
     public Guid? AssignedPartnerId {get;set;}
     public Partner AssignedPartner {get;set;}
}