防止数据网格加载C#中的Entity Framework导航属性

时间:2018-12-19 09:35:25

标签: c# winforms entity-framework entity-framework-6

我有一个数据库(具体来说是Firebird,但我认为问题与EF有关)。我已经使用数据库中的Code First生成了代码文件。例如,为驱动程序生成的代码是:

[Table("Firebird.DRIVER")]
public partial class DRIVER
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public DRIVER()
    {
        FAREs = new HashSet<FARE>();
    //..... and other code generated for the other collections
    }


    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int DRIVERID { get; set; }

    [StringLength(100)]
    public string FULLNAME { get; set; }
    //... and other properties


    public int? EQUIPMENTID { get; set; }

    public virtual EQUIPMENT EQUIPMENT { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<FARE> FAREs { get; set; }
    //.... and other code generated for the other collections

 }

我有一个带有DataGridView的基本表单。 DataGridView的目的是编辑,添加或删除新实体(驱动程序)。我这样绑定

    private async Task BindGrid()
    {
        var DBContext = AppVariables.CreateContext();
        await Task.Run(() => DBContext.DRIVERs.Load());
        var bindingSource = DBContext.DRIVERs.Local.ToBindingList();
        dataGridView1.DataSource = bindingSource;
    }

但是,我在网格中获得了导航属性(例如EQUIPMENT)。我该怎么做才能从加载到网格中删除导航属性。我应该先从代码中删除导航属性吗?还是有另一种方法可以在不加载导航属性的情况下将数据加载到网格中?

我尝试仅使用属性来创建对象,并避免使用导航,但是网格将不可编辑

    private async Task BindGrid()
    {
        var list = from driver in DBContext.DRIVERs
                   select new
                   {
                       DRIVERID = destination.DRIVERID
                       //...
                   };
        await list.LoadAsync();
        var bindingSource = list.ToBindingList();
        dataGridView1.DataSource = bindingSource;
    }

1 个答案:

答案 0 :(得分:1)

加载导航属性并显示它们是两个不同的主题。

防止加载

禁用延迟加载,仅包含所需的导航属性

var db = new MyDbContext(); 
db.Configuration.LazyLoadingEnabled = false; 
data = db.MyEntity.Local.ToBindingList();

防止显示

[Browsable(false)]装饰导航属性。

[Browsable(false)]
public virtual EQUIPMENT EQUIPMENT { get; set; }

将列可见性设置为false:

dataGridView1.Columns["EQUIPMENT"].Visible = false

首先,使用设计器或代码仅定义要用于DataGridView的一组列。然后DataGridView将仅显示您定义的那些列:

var DRIVERIDColumn = new DataGridViewTextBoxColumn();
DRIVERIDColumn.Name = "DRIVERID";
DRIVERIDColumn.HeaderText = "Id";
DRIVERIDColumn.DataPropertyName= "DRIVERID";
// ...
dataGridView1.Columns.AddRange(DRIVERIDColumn /*...*/);
// ...