如何为复杂关系构建此实体模型框架

时间:2015-06-03 16:55:32

标签: c# asp.net-mvc entity-framework

我有以下情况。我们需要能够填写一些表格的示例,例如公司(Empresa in Spanish),但我们希望管理员能够使用其他字段扩展实体本身。

我设计了以下类,我需要播种至少一行,但是我不清楚如何播种一行CampoAdicional

实体类:

 public abstract class Entidad
    {
        [Key]
        public int Id { get; set; }
    }

公司类(Empresas)

 public class Empresa : Entidad
    {

        public string Nombre { get; set; }
        public string NIT { get; set; }
        public string NombreRepresentanteLegal { get; set; }
        public string TelefonoRepresentanteLegal { get; set; }
        public string NombreContacto { get; set; }
        public string TelefonoContacto { get; set; }

        public virtual ICollection<CampoAdicional> CamposAdicionales { get; set; }

    }

附加场(Campo Adicional)

 public class CampoAdicional
    {
        [Key]
        public int Id { get; set; }
        public string NombreCampo { get; set; }
        public virtual Tiposcampo TipoCampo { get; set; }

        public virtual Entidad Entidad { get; set; }
    }

但是我不知道如何为这个类或表提供种子,因为实体应该是子类型Company

显然,typeof不编译

 context.CampoAdicionals.Add(new CampoAdicional() { Entidad = typeof(Empresa), Id = 1, NombreCampo = "TwitterHandle", TipoCampo = Tiposcampo.TextoUnaLinea });

更新1:请注意,其他字段适用于整个实体公司,不适用于每家公司。

1 个答案:

答案 0 :(得分:1)

不幸的是,我认为您无法使用EF自动创建这种关系。你可以用特殊的getter做类似的事情:

public class Entidad
{
    // stuff...

    public IEnumerable<CampoAdicional> CamposAdicionales 
    { 
       get { return CampoAdicional.GetAll(this); }
    }
}

public class CampoAdicional
{
    [Key]
    public int Id { get; set; }
    public string NombreCampo { get; set; }
    public virtual Tiposcampo TipoCampo { get; set; }

    protected string EntidadType { get; set; }

    // You will need some mapping between Type and the EntidadType string
    // that will be stored in the database. 
    // Maybe Type.FullName and Type.GetType(string)?
    protected Type MapEntidadTypeToType();
    protected string MapTypeToEntidadType(Type t);

    [NotMapped]
    public Type 
    {            
        get { return MapEntidadTypeToType(); }
        // maybe also check that Entidad.IsAssignableFrom(value) == true
        set { EntidadType = MapTypeToEntidadType(value); }
    }

    public static IEnumerable<CampoAdicional> GetAll(Entidad ent)
    {
        return context.CampoAdicionals
            .Where(a => a.EntidadType == MapTypeToEntidadType(ent.GetType()));
    }
}
相关问题