我目前正面臨這個問題。我通過LINQ to SQL將POCO手動映射到我的數據庫表中。我希望將所有這些對象/表放在一個上下文中(作爲事務處理),以便在事務中出現故障時,所有對象都會回滾。LINQ to SQL 1:1插入
現在我面臨的問題是我有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()。
這是真正的問題用武之地。用戶配置的ID仍然爲0。
誰能幫助?
對不起,我沒有說清楚。在使用中的SQL Server是MS SQL Server 2008的
的實體結構是這樣的,
用戶登陸是在註冊時必需的,而用戶配置不是,使其成爲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,或者至少,這是我的一廂情願。
在我的用戶配置,我有這樣的片段:
[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; } }
在我的用戶登陸,我有以下片段:
[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 ...添加一個序列...? – esastincy