我理解错误,问题是如何告诉EF在UserSettings之前插入用户记录?
我正在尝试设置1对1的关系,其中User表可以在没有UserSettings的情况下存在,但UserSettings只有在有User的情况下才能存在。为此,我设置了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.SaveChanges()抛出以下异常:
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 :(得分: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属性和导航属性解决了这个问题。