2017-05-26 80 views
0

我理解錯誤,問題是如何告知EF在UserSettings之前插入用戶記錄?EF - INSERT語句與FOREIGN KEY約束衝突

我想建立一個1對1的關係,用戶表可以存在沒有UserSettings,但UserSettings只能存在,如果有用戶。爲了做到這一點,我設置了UserSettings表,使其主鍵也是外鍵;也許這是不好的設計,想法?這裏是兩個表創建腳本:

CREATE TABLE [dbo].[Users] 
(
    [Userid] UNIQUEIDENTIFIER NOT NULL PRIMARY KEY, 
    [UserName] NVARCHAR(MAX) NOT NULL, 
    CONSTRAINT [PK_Users] PRIMARY KEY ([Userid]) 
) 

這裏是UserSettings表:

CREATE TABLE [dbo].[UserSettings] 
(
    [UserId] [uniqueidentifier] NOT NULL, 
    [SettingOne] [bit] NOT NULL, 
    [SettingTwo] [bit] NOT NULL, 
    [SettingThree] [bit] NOT NULL, 
    CONSTRAINT [PK_UserSettings] PRIMARY KEY ([UserId]), 
    CONSTRAINT [FK_UserSettings_Users] FOREIGN KEY ([UserId]) REFERENCES [Users]([UserId]), 
) 

這是我的實體是如何設置的:

public class User 
{ 
    [Key] 
    public Guid UserId { get; set; } 
    public string UserName { get; set; } 
    [ForeignKey("UserId")] 
    public UserSetting UserSetting { get; set; } 
} 

public class UserSetting 
{ 
    [Key] 
    public Guid UserId { get; set; } 
    public bool SettingOne { get; set; } 
    public bool SettingTwo { get; set; } 
    public bool SettingThree { get; set; } 
} 

當我運行以下:

static void Main(string[] args) 
{ 

    using (var db = new SandBoxContext()) 
    { 
     var userId = Guid.NewGuid(); 
     db.Users.Add(new User() 
     { 
      UserId = userId, 
      UserName = "Bob", 
      UserSetting = new UserSetting() 
      { 
       UserId = userId, 
       SettingOne = true, 
       SettingTwo = false, 
       SettingThree = true 
      } 
     }); 

     db.SaveChanges(); 
    } 

    Console.ReadKey(); 
} 

db.Sa veChanges()拋出下面的異常:

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_UserSettings_Users". The conflict occurred in database "SandBox", table "dbo.Users", column 'UserId'. 

回答

0

我剛剛發現http://www.entityframeworktutorial.net

的答案,我不得不改變UserSettings類這樣的:

public class UserSetting 
{ 
    [Key, ForeignKey("User")] 
    public Guid UserId { get; set; } 
    public bool SettingOne { get; set; } 
    public bool SettingTwo { get; set; } 
    public bool SettingThree { get; set; } 

    public virtual User User { get; set; } 
} 

包括ForeignKey的屬性和導航財產解決了這個問題。

相關問題