我非常难以确定何时应该附加到对象,何时不应该附加到对象。首先,这是我的(非常简化的)对象模型的小图示。
在我的数据访问层中,每次进行与数据相关的操作时,我都会创建一个新的DataContext。例如,如果我想保存一个新用户,我会在业务层中创建一个新的用户。
var user = new User();
user.FirstName = "Bob";
user.LastName = "Smith";
user.Username = "bob.smith";
user.Password = StringUtilities.EncodePassword("MyPassword123");
user.Organization = someOrganization; // Assume that someOrganization was loaded and it's data context has been garbage collected.
现在我想去保存这个用户。
var userRepository = new RepositoryFactory.GetRepository<UserRepository>();
userRepository.Save(user);
太棒了!这是我的保存逻辑:
public void Save(User user)
{
if (!DataContext.Users.Contains(user))
{
user.Id = Guid.NewGuid();
user.CreatedDate = DateTime.Now;
user.Disabled = false;
//DataContext.Organizations.Attach(user.Organization);
DataContext.Users.InsertOnSubmit(user);
}
else
{
DataContext.Users.Attach(user);
}
DataContext.SubmitChanges();
// Finished here as well.
user.Detach();
}
所以,我们来到了这里。你会注意到我注释掉了将DataContext附加到组织的部分。如果我附加到组织,我会得到以下异常:
NotSupportedException: 尝试附加或添加不是新的实体, 可能已从另一个DataContext中加载。 这是不支持的。
嗯,那样行不通。让我试试不附加(即注释掉关于附加到组织的那行代码)。
DuplicateKeyException: 无法添加具有已经使用的密钥的实体。
什么?我只能假设这是在尝试插入一个新的组织,这显然是错误的。
那么,怎么办呢?应该怎么做?正确的方法是什么?看起来L2S使这比它本应该更难...
编辑: 我刚刚注意到,如果我尝试查看待处理的更改集 (dataContext.GetChangeSet()),我会得到我之前描述的相同的NotSupportedException!L2S到底是怎么回事?!