我有一个奇怪的情况,我无法弄清楚原因。在Windows Phone应用程序启动时,我有以下代码,我只是创建一些Group
,然后创建一些Account
s,其中先前创建的Group
是与之相关的对象Account
秒。
public async static void SampleData()
{
var grp1 = await Manager.GroupManager.SaveGroupAsync(new Group { GroupName = "Wells Fargo" });
var grp2 = await Manager.GroupManager.SaveGroupAsync(new Group { GroupName = "Chase" });
var grp3 = await Manager.GroupManager.SaveGroupAsync(new Group { GroupName = "Citi" });
var acct1 = await Manager.AccountManager.SaveAccountAsync(new Account { AccountName = "Spending", AccountType = (int)Enums.AccountType.Banking, Group = grp1 }); //0
var acct2 = await Manager.AccountManager.SaveAccountAsync(new Account { AccountName = "Credit Card", AccountType = (int)Enums.AccountType.Credit, Group = grp1 }); //1
var acct3 = await Manager.AccountManager.SaveAccountAsync(new Account { AccountName = "Mortgage", AccountType = (int)Enums.AccountType.Banking, Group = grp2 }); //2
var acct4 = await Manager.AccountManager.SaveAccountAsync(new Account { AccountName = "Savings", AccountType = (int)Enums.AccountType.Banking, Group = grp2 }); //3
var acct5 = await Manager.AccountManager.SaveAccountAsync(new Account { AccountName = "Spending", AccountType = (int)Enums.AccountType.Banking, Group = grp2 }); //4
var acct6 = await Manager.AccountManager.SaveAccountAsync(new Account { AccountName = "Credit Card", AccountType = (int)Enums.AccountType.Credit, Group = grp3 }); //5
}
各种方法:
管理员
public async static Task<Group> SaveGroupAsync(Group group)
{
await DataAccess.GroupData.SaveGroupAsync(group);
return group;
}
public async static Task<Account> SaveAccountAsync(Account account)
{
await DataAccess.AccountData.SaveAccountAsync(account);
return account;
}
数据访问
public async static Task<Group> SaveGroupAsync(Group group)
{
using (var dc = new CbmDataContext(DBHelper.LocalConnectionString))
{
if (group.GroupId == 0)
dc.Groups.InsertOnSubmit(group);
dc.SubmitChanges();
return group;
}
}
public async static Task<Account> SaveAccountAsync(Account account)
{
using (var dc = new CbmDataContext(DBHelper.LocalConnectionString))
{
if (account.AccountId == 0)
dc.Accounts.InsertOnSubmit(account);
dc.SubmitChanges();
return account;
}
}
当群组的前三个保存运行时,我看到插入了3个新对象。这是我的预期行为。当代码针对第一个新帐户运行时,我会看到新帐户,但我还在“组”表中看到引用帐户的新条目。我最终得到了2个同名的组。
我做错了什么才允许这种情况发生?我可以看到Account.GroupId设置为下面设置的组的Id。
答案 0 :(得分:0)
所以我偶然发现了解决方案,但没有那么多答案。
我从这里的一个答案的评论中找到了方向 - LINQ to SQL - where does your DataContext live?
据我所知,您仍然需要一个DataContext来管理Entity的生命周期,以便SubmitChanges()正常工作而无需重新附加您的实体。正确? Fetch-&GT;编辑 - &GT;提交。在这种情况下,您的DataContext位于方法范围之外,“使用”的价值较低。
在其他DAO继承的BaseData类上,我抛出了数据上下文的静态实例,刚刚从DAO中删除了所有的使用,所以现在他们使用相同的数据上下文。
public static CbmDataContext dc = new CbmDataContext(DBHelper.LocalConnectionString);
所以我想因为我在这里使用相同的数据上下文实例,它能够更好地跟踪实体,而不是新实例。