【问题标题】:Entity Framework disable loading virtual members实体框架禁用加载虚拟成员
【发布时间】:2017-12-20 00:40:26
【问题描述】:

我已经使用 SSMS 创建了一个数据库。然后我完成了整个 C# 项目并使用 NuGet 安装了 EF。我希望 EF 为我创建所有类和上下文,所以我从数据库执行 Code First,它为我做到了。现在 Product 类看起来像这样:

    public partial class Product
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Product()
        {
            Orders = new HashSet<Order>();
        }

        public int ID { get; set; }

        [Required]
        [StringLength(50)]
        public string Name { get; set; }

        public int Type_ID { get; set; }

        public decimal Price { get; set; }

        public string Descryption { get; set; }

        public int Available_amount { get; set; }

        public virtual Product_Type Product_Type { get; set; }

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

问题是,Product 表是这样的:

它与OrdersProduct_Type 表有关。现在,当我想获取所有产品并将它们移至dataGridView 时 - 会发生这种情况:

获取产品的代码:

public void GetProducts()
{
    using (var db = new SklepContext())
    {
        var data = db.Products.ToList();
        dataGridViewBrowse.DataSource = data;
    }
}

效果:

首先它在我脸上抛出错误,所以我不得不添加这一行 this.Configuration.ProxyCreationEnabled = false; 在我的 SklepContext 构造函数中。

问题是我该怎么做才能让它不读取那些虚拟成员(不知道为什么 EF 首先会添加它们)或让 EF 在没有它们的情况下创建这些类(我不能通过删除它们来删除它们Product 类中的 2 行),所以我的 dataGridView 只显示数据库中的值?

【问题讨论】:

标签: c# entity-framework datagridview


【解决方案1】:

如果你突然说,你的标题很容易误导

在将数据绑定到 dataGridView 时,我只是不想要最后两列

这两列出现在您的dataGridView 中的原因是您直接绑定模型。

这里有一些替代方案:

1.绑定后移除列。

dataGridView1.Columns.RemoveAt(dataGridView1.Columns.Count - 1);
dataGridView1.Columns.RemoveAt(dataGridView1.Columns.Count - 1);

2.为绑定创建不同的视图模型

public class DataGridViewModel
{   
    public int ID { get; set; }

    public string Name { get; set; }

    public int Type_ID { get; set; }

    public decimal Price { get; set; }

    public string Descryption { get; set; }

    public int Available_amount { get; set; }

    public DataGridViewModel()  
    {    
    }
}

public void GetProducts()
{
    using (var db = new SklepContext())
    {
        var data = db.Products.Select(r => new DataGridViewModel()
        {
            ID  = r.ID,
            Name = r.Name,
            Type_ID = r.Type_ID,
            Price = r.Price,
            Descryption = r.Descryption,
            Available_amount = r.Available_amount
        }).ToList();
        dataGridViewBrowse.DataSource = data;
    }
}

【讨论】:

  • 我已经做了第二件事,但非常感谢第一件事!
猜你喜欢
  • 2013-01-24
  • 2012-06-29
  • 1970-01-01
  • 2011-09-07
  • 2016-05-29
  • 1970-01-01
  • 1970-01-01
  • 2017-07-28
  • 1970-01-01
相关资源
最近更新 更多