[英]EF6/LINQ MySQL - Won't Insert
Using EF6/LINQ with a MySQL server. 在MySQL服务器上使用EF6 / LINQ。 I have a DataGridView binded to a BindingList of Entities using a DataTable.
我有一个使用DataTable绑定到实体的BindingList的DataGridView。 Everything works fine, even deleting records.
一切正常,甚至删除记录。 But I can't insert records that have not already been in the database.
但是我无法插入数据库中尚未存在的记录。
What I mean by this is that if I select a record from the database, then delete it, SaveChanges(), and then reinsert it, it reinserts itself! 我的意思是,如果我从数据库中选择一条记录,然后将其删除,SaveChanges(),然后重新插入,它将重新插入自身! But if I try to insert ex.
但是,如果我尝试插入前。 new tcompanyaddress(), set its properties, and insert it?
新的tcompanyaddress(),设置其属性,然后插入? Doesn't work.
不起作用
The ultimate goal is to emulate a transaction clearing all addresses associated with a CompanyID FK in the DB, then simply reinserting the most current edited addresses from the BindingList. 最终目标是模拟事务,清除数据库中与CompanyID FK相关的所有地址,然后仅从BindingList中重新插入最新编辑的地址。 Again, it works... but not on new entries.
同样,它可以工作...但不适用于新条目。
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();
}
Solution was simple. 解决方案很简单。 Turns out I wasn't setting the CompanyID FK when I added a new address to the BindingList, which meant the query never selects it.
原来,当我向BindingList添加新地址时,我没有设置CompanyID FK,这意味着查询从不选择它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.