【发布时间】:2017-05-26 02:27:21
【问题描述】:
我理解错误,问题是如何告诉 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'.
【问题讨论】:
标签: entity-framework