实体框架查找不起作用,我不知道为什么

时间:2018-04-10 09:52:17

标签: c# .net entity-framework find dbcontext

我实际上正在处理一个与实体框架一起工作的现有项目,它首先使用代码,我添加了2个实体,一个“Profil”实体和一个具有多对多关系的“ActionHyperV”实体,我正确地拥有迁移现有数据库并创建了我的表,以及链接我的两个实体的ProfilActionHyperVs表。 这是我的两个实体:

public class Profil
{

    public int Id { get; set; }
    [StringLength(50)]
    public string Nom { get; set; }
    [StringLength(250)]
    public string Commentaire { get; set; }

    public ICollection<ActionHyperV> ActionHyperVs { get; set; }
}


public class ActionHyperV
{

    public int Id{ get; set; }
    [StringLength(50)]
    public string Nom { get; set; }
    [StringLength(250)]
    public string Commentaire { get; set; }

    public ICollection<Profil> Profils { get; set; }
}

如果我这样做,我可以拥有表格的内容:

List<Profil> profils = ctx.Profils.ToList();

有效。

但我想要做的是链接我的表格,所以我喜欢这样:

public bool LinkProfilAction(/*int ProfilID, int ActionID*/)
        {

                using (Context ctx = this._contextProvider.GetContext())
                {

                int ProfilID = 1;
                int ActionID = 1;

                var profil = ctx.Profils.Find(ProfilID);
                var action = ctx.ActionHyperV.Find(ActionID);


                profil.ActionHyperVs.Add(action);

                ctx.SaveChanges();
                return true;

                }


        }

如果我在之前存在但不在Profil和ActionHyperV表上的表上执行它,那么它会起作用,find返回null,我不知道为什么因为我填充了我的表并使用了正确的ID来查看对于我的数据。 我试着在插入部分的下一个教程中做到这一点,这正是我想做的事情,但它做了同样的事情。

如果你知道什么是错的,那将是非常有帮助的。 谢谢!

1 个答案:

答案 0 :(得分:0)

您似乎忘了在您的收藏中添加虚拟属性。使用代理模式的实体框架需要覆盖您的类。 试试这个:

public virtual ICollection<ActionHyperV> ActionHyperVs { get; set; }

public virtual ICollection<Profil> Profils { get; set; }