实体框架:使用外键保存对象而不在引用表中插入新对象

时间:2017-08-02 14:20:26

标签: entity-framework-core

我有两个表,它们是先使用Entity Framework Core代码创建的。 一个ApplicationUser和他的ColorThemeSetting。创建新用户时,还会生成新的ColorThemeSetting。但是当我保存时,会出现此错误:

  

INSERT语句与FOREIGN KEY约束冲突   “FK_ColorThemeSetting_AspNetUsers_SettingsOwnerId”。冲突   发生在数据库“MyDb”,表“dbo.AspNetUsers”,列“Id”中。   声明已经终止。

我认为EF尝试从外键id添加新用户。我怎么能防止这种情况? 添加新的ColorThemeSetting:

//user and appUser are correctly initialized
var themeConfig = new ColorThemeSetting();
themeConfig.PrimaryColor = user.PrimaryColor ?? "";
themeConfig.SecondaryColor = user.SecondaryColor ?? "";
themeConfig.SettingsOwnerId = appUser.Id;
unitOfWork.ColorThemeSettings.Add(themeConfig);

ColorThemeSetting类:

public class ColorThemeSetting
{
    public string PrimaryColor { get; set; }
    public string SecondaryColor { get; set; }

    public string SettingsOwnerId { get; set; }
    [ForeignKey("SettingsOwnerId")]
    public virtual ApplicationUser SettingsOwner { get; set; }
}

0 个答案:

没有答案