我有两个模型:
class ModelA
{
public Id {get; set;}
public int? ModelBId { get; set; }
public ModelB ModelB { get; set; }
}
class ModelB
{
public int Id { get; set; }
}
,当我尝试仅添加ModelA(ModelBId为int?
)时:
var model = new ModelA();
context.ModelAs.Add(model); // after this step ModelB is already set to not null
context.SaveChanges();
EF Core 2.2插入了ModelA和ModelB ...为什么?我只需要添加具有空ModelB的ModelA ...在EF6中就可以使用...
答案 0 :(得分:-1)
像这样显式定义外键:
class ModelA
{
public Id {get; set;}
[ForeignKey("ModelB")]
public int? ModelBId { get; set; }
public ModelB ModelB { get; set; }
}
或
class ModelA
{
public Id {get; set;}
public int? ModelBId { get; set; }
[ForeignKey("ModelBId")]
public ModelB ModelB { get; set; }
}