简体   繁体   English

实体框架SaveChanges()不反映在实体上

[英]Entity Framework SaveChanges() not reflecting on entities

I have a Winforms project and a database running on SQL Server which has 2 tables, Student and Standard . 我有一个Winforms项目和一个在SQL Server上运行的数据库,该数据库有2个表StudentStandard

First I created an ADO.NET Entity Data Model from the database with the wizard help thing. 首先,我使用向导帮助从数据库创建了一个ADO.NET实体数据模型。 Then I have a DataGridView control which has a bindingsource as DataSource. 然后,我有一个DataGridView控件,该控件具有一个绑定源作为DataSource。

NOTE: DataBindingProjection is a class that I created to be able to populate DataGridView with properties from both Student and Standard entities 注意: DataBindingProjection是我创建的一个类,该类能够使用StudentStandard实体的属性填充DataGridView

I have this code: 我有以下代码:

var query = context.Students
                  .Include(s => s.Standard)
                  .Select(s => new DataBindingProjection
                  {
                      StudentID = s.StudentID,
                      StudentName = s.StudentName,
                      DateOfBirth = s.DateOfBirth,
                      Height = s.Height,
                      Weight = s.Weight,
                      StandardName = s.Standard.StandardName,
                      Standard_StandardId = s.Standard.StandardId
                  }).ToList();

            myList = new BindingList<DataBindingProjection>(query.ToList());
            dataBindingProjectionBindingSource.DataSource = myList;
            dataBindingProjectionDataGridView.DataSource = dataBindingProjectionBindingSource;

the grid is populated however, when I call context.SaveChanges() , it doesn't update the database. 但是,当我调用context.SaveChanges() ,不会填充数据库,它不会更新数据库。

Using Select method on DbSet to project data to non-entity class will destroy the link to the original data. DbSet上使用Select方法将数据投影到非实体类将破坏到原始数据的链接。 In your case, you should bind to Student class directly. 对于您的情况,您应该直接绑定到Student类。

To bind to properties in Standard class, you can extends Student by adding property to it because it is a partial class. 要绑定到Standard类中的属性,您可以通过向其添加属性来扩展Student ,因为它是部分类。

partial class Student {
    public StandardName { 
       get { return this.Standard.StandardName; }
       set { this.Standard.StandardName = value; }
    }
}

Assuming that Standard property will never be null. 假设Standard属性永远不会为null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM