【发布时间】:2011-04-04 12:01:21
【问题描述】:
下午好-
我正在为数据访问层使用 LINQ to Entity Framework 开发 Silverlight 应用程序。我的 n 层数据库模型包括大约 30 个左右的表,其中包含许多多层次的父子关系。最近开始编写我的数据服务和单元测试,并发现在父表记录已定义时将新记录插入子表的问题。这是我的父表和子表的精简版:
父表:
用户
用户 ID (PK)
电子邮件
密码
等等……
儿童桌:
用户配置文件
用户配置文件 ID (PK)
各种个人资料信息...
UserID(FK -- 用户表)
所以此时,我已经使用实体框架为 ORM 创建了各种类,并且我正在寻找为我的实体上的 CRUD 操作创建数据服务。以下是我插入新 User(没有父表引用)的方法的示例代码:
public User CreateUser(User newUser)
{
using (var _context = new ProjectDatabase())
{
newUser.CreatedDate = DateTime.Now;
newUser.ModifiedDate = DateTime.Now;
_context.AddToUsers(newUser);
_context.SaveChanges();
}
return newUser;
}
这很好用。我已经为它编写了单元测试,没问题。现在,另一方面,考虑我编写的以下数据服务方法,用于将新的 UserProfile 对象插入数据库。首先,我有一个非常相似的数据服务:
public UserProfile CreateProfile(UserProfile newUserProfile)
{
using (var _context = new ProjectDatabase())
{
newUserProfile.CreatedDate = DateTime.Now;
newUserProfile.ModifiedDate = DateTime.Now;
_context.AddToUserProfiles(newUserProfile);
_context.SaveChanges();
}
return newUserProfile;
}
此代码与其他代码一样,可以毫无问题地编译。但是,我的单元测试始终失败。这是我的单元测试的代码:
[TestMethod]
public void UserProfileCrudTest()
{
IProfileDataService _dataService = new ProfileDataService();
// Pre-seeded data on a State for foreign key
State _myState;
using (var _context = new ProjectDatabase())
{
_myState = _context.States.First();
}
// Creating temporary User for association with new UserProfile
User _myUser = new User()
{
Email = "test",
Password = "test",
IsActive = true,
NameFirst = "test",
NameLast = "test"
};
_myUser = _dataService.CreateUser(_myUser);
Assert.IsNotNull(_myUser);
// Attempt to create new UserProfile, assigning foreign key
_myUserProfile = new UserProfile()
{
Address = "123 Main",
City = "Anywhere",
State = _myState,
PostalCode = "63021",
UserID = _myUser.UserID
};
// This call to CreateProfile throws an exception and the test fails!!
_myUserProfile = _dataService.CreateProfile(_myUserProfile);
Assert.IsNotNull(_myUserProfile);
// Remaining test code... never gets this far...
}
所以此时,我的单元测试抛出以下异常:
测试方法 MyProject.DataServices.Tests.SecurityTests.UserProfileCrudTest 抛出异常: System.InvalidOperationException:EntityKey 属性只有在属性当前值为空时才能设置。
据我目前的研究了解,这以某种方式与导航属性相关联,该属性将新的 UserProfile 对象与父表/对象上的 User.UserProfiles 集合相关联。但我不确定解决问题需要哪些步骤。我是否需要以某种方式将父级附加到 ObjectContext?任何帮助将不胜感激!
谢谢, 杰夫·S.
【问题讨论】:
标签: entity-framework-4 parent-child wcf-data-services