簡體   English   中英

如何為復雜關系建立實體模型框架的種子

[英]How to seed this entity model framework for complex relationship

我有以下情況。 我們需要能夠填寫一些表格的表格,例如公司(西班牙語中的Empresa),但是我們希望管理員能夠使用其他字段來擴展實體本身。

我設計了以下課程,需要播種至少一排,但是我不清楚如何播種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:請注意,其他字段適用於整個實體公司,而不適用於每個公司。

不幸的是,我認為您將無法使用EF自動創建這種關系。 您也許可以使用特殊的吸氣劑進行類似的操作,例如:

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()));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM