【发布时间】:2011-09-15 09:04:57
【问题描述】:
我目前正面临这个问题。我有 POCO 通过 LINQ to SQL 手动映射到我的数据库表。我希望将所有这些对象/表放在一个上下文中(视为事务),这样如果一个事务失败,所有对象/表都会回滚。
现在我面临的问题是我有 UserLogin 和 UserProfile(1 : 0 - 1 关系)。它们的结构方式是,UserLogin 的 id 是 UserProfile 的 PK 和 FK,UserProfile 也是如此。在 UserLogin 上,它设置为自动生成身份,并将 IsDBGenerated 设置为 true。另一方面,UserProfile 没有 IsDBGenerated。
UserProfile 在 UserLogin 中设置为 EntityRef,由于它们来自相同的上下文,因此我在创建时设置了 UserLogin.UserProfile = new UserProfile()。
分配所有属性后,我做了 table.InsertOnSubmit(UserLogin) 和 context.SaveChanges()。
这才是真正的问题所在。UserProfile 的 id 保持为 0。
谁能帮忙?
对不起,我没有说清楚。使用的 SQL Server 是 MS SQL Server 2008。
实体结构是这样的,
UserLogin 在注册时是强制性的,而 UserProfile 不是,这使其成为 1 : 0 - 1 的关系。因此,在两个表上都自动递增是不明智的。
UserProfile 的 PK 也是一个引用 UserLogin 的 FK。
@GertArnold,是的,我确实在 asp.net 代码隐藏中设置了 UserProfile id = UserLogin id,但在保存上下文之前,UserLogin 的 id 将保持为 0,因为此时我希望将两条记录添加在一起并且想知道如果 Linq to Sql 有办法解决这个问题。由于我添加了 Association 属性,因此 Linq to Sql 应该能够识别这种依赖关系并在提交时添加 id,或者至少,这是我的一厢情愿。
在我的 UserProfile 中,我有这个 sn-p:
[Column(IsPrimaryKey = true)]
public long id { get; set; }
private EntityRef<UserLogin> _login;
[Association(ThisKey = "id", Storage = "_login")]
public UserLogin UserLogin { get { return _login.Entity; }
set { _login.Entity = value; } }
在我的 UserLogin 中,我有以下 sn-p:
[Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]
public long id { get; set; }
private EntityRef<UserProfile> _profile;
[Association(ThisKey = "id", Storage = "_profile")]
public UserProfile UserProfile { get { return _profile.Entity; }
set { _profile.Entity = value; } }
最后,在我的代码隐藏中,我有这个:
UserLogin login = new UserLogin();
// All assigning here
login.UserProfile = new UserProfile();
// Assign here
login.userProfile.id = login.id;
此时,两个 id 都为零,因为还没有插入任何一个。
当我执行 context.SubmitChanges() 时,UserLogin 的 id 将获得递增值,但 UserProfile 的 id 将保持为 0。我想将两者包装在同一个上下文中并一起提交的原因是为了避免像 UserLogin 被提交这样的情况,但 UserProfile 遇到错误。所以在我的数据库中,有登录记录但没有个人资料,这弄乱了我的数据。
【问题讨论】:
-
您使用的是什么类型的数据库?由于 UserProfile 是 UserLogin 的子记录(至少在我看来是这样),为什么你不能让 UserProfile.Id 成为 SqlServer 中的 AutoIncremting 字段,如果它的 Oracle 则添加一个序列......?
标签: linq linq-to-sql database-design foreign-keys