保存不为其关系公开外键的实体

时间:2017-07-01 10:05:01

标签: c# entity-framework foreign-keys

我在EF代码中有点新鲜。让我们说我有两个实体如下 -

//Parent may have many childs
class Parent
{
    [Key]
    public int ParentId { get; set; }
    public string ParentName {get; set; }
    public virtual ICollection<Child> Childs { get; set; }
}

//Child will have one parent.
class Child
{
    [Key]
    public int ChildId { get; set; }
    public string ChildName {get; set; }
    public int ParentId {get; set; }
    public virtual Parent Parent{ get; set; }
}

我想保存为 -

var parent= db.Parents.find(1);
var child=new Child();
....
child.Parent= parent
db.Childs.Add(child);
db.SaveChanges();

但它给了我以下例外 -

an error occurred while saving entities that do not expose foreign key for their relationship.

也许,我在这里遗漏了一些东西。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

你是否用流畅的api定义了关系?如果不是,您必须通过属性或流畅的api定义它。像这样:

//Child will have one parent.
class Child

{
    [Key]
    public int ChildId { get; set; }
    public string ParenChildName {get; set; }
    public int ParentId {get; set; }
    [ForeignKey("ParentId")]
    public virtual Parent Parent{ get; set; }
}

同样设置子级的Parent属性也无济于事,因为父级由ParentId属性定义,您必须设置ParentId=parent.ParentId