EF Core为什么会自动生成空属性

时间:2019-09-23 17:37:40

标签: c# entity-framework-core

我有两个模型:

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中就可以使用...

1 个答案:

答案 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; }
}