kob*_*490 4 entity-framework code-first ef-code-first entity-framework-6
我有以下情况:
颜色等级
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
public string Hex
{
get;
set;
}
Run Code Online (Sandbox Code Playgroud)小部件类
public int ID
{
get;
set;
}
public int HeaderBackgroundColorID
{
get;
set;
}
public Color HeaderBackgroundColor
{
get;
set;
}
Run Code Online (Sandbox Code Playgroud)使用Code-First,我尝试使用HeaderBackgroundColor / HeaderBackgroundColorID字段在Widget到Color类之间创建单向关系。
通常我会在config类中这样做:
this.HasOptional(r => r.HeaderBackgroundColor )
.WithMany(m => m.Widgets)
.HasForeignKey(fk => fk.HeaderBackgroundColorID);
Run Code Online (Sandbox Code Playgroud)
但是我不喜欢将Widgets集合添加到Color类。尝试了这个:
this.HasOptional(r => r.HeaderBackgroundColor )
.WithMany()
.HasForeignKey(fk => fk.HeaderBackgroundColorID);
Run Code Online (Sandbox Code Playgroud)
但这会引发验证错误。
正确的方法是什么?
您收到一个错误,因为它HeaderBackgroundColorId是一个不可为null的变量int,因此它不是可选的。
您需要完成的所有工作就是将外键转换为可为空的值int...
public int? HeaderBackgroundColorID { get; set; }
Run Code Online (Sandbox Code Playgroud)
因为您已命名外键来匹配遵循Code First约定的导航属性(HeadBackgroundColorId和HeaderBackgroundColor),所以您无需创建任何显式映射。简单地进行上述更改将使该关系成为可选关系。