为什么EF 6会自动删除实体类中的覆盖方法?

时间:2017-02-13 17:47:28

标签: c# winforms entity-framework

我在模型clases中包含一个覆盖方法来获取与索引相关的值,例如:City表与Country表相关,所以如果我将gridview数据源设置为table.toList(),则添加id_country索引字段,通过覆盖类中的ToString()方法,您可以在网格中设置国家/地区名称的返回,它可以工作,但有时EF模型删除覆盖方法,并且不再返回该值。这是具有覆盖方法的EF自动生成的类,但最终它将被EF删除:

public partial class pais
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public pais()
    {
        this.comprador_vendedor = new HashSet<comprador_vendedor>();
        this.estado = new HashSet<estado>();
        this.exportacion = new HashSet<exportacion>();
    }

    public int id_pais { get; set; }
    public string nombre { get; set; }

    public override string ToString()
    {
        return nombre;
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<comprador_vendedor> comprador_vendedor { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<estado> estado { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<exportacion> exportacion { get; set; }
}

1 个答案:

答案 0 :(得分:3)

每次更改模型时都会覆盖生成的类。

因此顶部的警告

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated from a template.
//
//     Manual changes to this file may cause unexpected behavior in your application.
//     Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

如果要扩展类,只需在同一名称空间中创建另一个具有相同名称的部分类