将EF6 / LINQ与MySQL服务器配合使用。我有一个DataGridView使用DataTable绑定到实体的BindingList。一切正常,甚至删除记录。但我无法插入尚未存在于数据库中的记录。
我的意思是,如果我从数据库中选择一条记录,然后删除它,SaveChanges(),然后重新插入它,它会重新插入它自己!但是,如果我尝试插入前。 new tcompanyaddress(),设置其属性,并插入它?不行。
最终目标是模拟事务清除与DB中的CompanyID FK关联的所有地址,然后只需从BindingList重新插入最新编辑的地址。同样,它有效......但不适用于新条目。
using (JobTrackerEntities context = new JobTrackerEntities())
{
context.Database.Connection.ConnectionString += ";password=orbitman1;";
// Update main profile
tcompany companyRow = context.tcompany.Find(Company.CompanyID);
companyRow.CompanyName = Company.CompanyName;
// Update foreign profiles
var addresses = from address in context.tcompanyaddress // Retreive all addresses that were removed
where address.CompanyID == Company.CompanyID
select address;
// Clear existing addresses
foreach (tcompanyaddress address in addresses)
{
Console.WriteLine("Remove " + address.LocationName);
context.Entry(address).State = EntityState.Deleted;
}
addresses = from address in context.tcompanyaddress // Retreive all addresses that were removed
where address.CompanyID == Company.CompanyID
select address;
Console.WriteLine("After clear: " + addresses.Count());
// Replace with new addresses
foreach (tcompanyaddress address in CompanyAddresses)
{
Console.WriteLine("Add " + address.LocationName);
context.tcompanyaddress.Add(address);
}
// Commit transaction
context.SaveChanges();
addresses = from address in context.tcompanyaddress // Retreive all addresses that were removed
where address.CompanyID == Company.CompanyID
select address;
Console.WriteLine("After add: " + addresses.Count());
RefreshProfileForm();
}
答案 0 :(得分:0)
解决方案很简单。当我向BindingList添加一个新地址时,我没有设置CompanyID FK,这意味着查询永远不会选择它。