我正在学习LINQ/EF,我已经编写了以下代码段。创建/读取/更新工作,但Delete引发InvalidOperationException。当我将鼠标悬停在错误上时,它显示Customer对象的空值。
有什么想法吗?
HTML代码
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="CustomersODS">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
</Columns>
</asp:GridView>
<asp:ObjectDataSource ID="CustomersODS" runat="server"
DataObjectTypeName="CustOrderTest.Models.Customer"
DeleteMethod="Customer_Delete" SelectMethod="Customers_GetAll"
TypeName="CustOrderTest.Models.CustomerModel" UpdateMethod="Customer_Update">
</asp:ObjectDataSource>
方法库
namespace CustOrderTest.Models
{
public class CustomerModel
{
COContext DB = new COContext();
public List<Customer> Customers_GetAll()
{
return (from customer in DB.Customers
select customer).ToList();
}
public List<Customer> Customers_Search(string CustomerName)
{
return (from customer in DB.Customers
where customer.Name.Contains(CustomerName)
select customer).ToList();
}
public Customer Customer_GetByID(int? ID)
{
return (from customer in DB.Customers
where customer.ID == ID
select customer).FirstOrDefault();
}
public void Customer_Update(Customer customer)
{
DB.Entry(customer).State = EntityState.Modified;
DB.SaveChanges();
}
public void Customer_Insert(Customer customer)
{
DB.Customers.Add(customer);
DB.SaveChanges();
}
public void Customer_Delete(Customer customer)
{
DB.Customers.Remove(customer);
DB.SaveChanges();
}
}
}
数据模型//
namespace CustOrderTest.Models
{
public class Customer
{
public int ID { get; set; }
public string Name { get; set; }
}
public class CustomerOrder
{
public int ID { get; set; }
public Customer Customer { get; set; }
public DateTime OrderDate { get; set; }
public int MyProperty { get; set; }
public List<CustomerOrderDetail> OrderDetails { get; set; }
}
public class CustomerOrderDetail
{
public int ID { get; set; }
public string Part { get; set; }
public int Quantity { get; set; }
public double Price { get; set; }
}
public class COContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<CustomerOrder> CustomerOrders { get; set; }
public DbSet<CustomerOrderDetail> OrderDetails { get; set; }
}
}
愚蠢的错误-答案如下。如果您出现此错误,很可能是您没有指定DataKeyNames
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="CustomersODS">