【问题标题】:I get UpdateException when i try to Update a collection property当我尝试更新集合属性时出现 UpdateException
【发布时间】:2014-01-11 02:17:35
【问题描述】:

我在一个 MVC4 应用程序中,我正在使用 EF CodeFirst。 当我尝试运行以下代码时:

 public void Autorizare(int cerereId, Persoana persoana)
        {

            var cerere = _db.Cereri.Find(cerereId);
            cerere.Autorizare.Add(persoana);            
            _db.SaveChanges();
        }

我收到这样的错误:

Entities in 'CerereDbContext.Persoane' participate in the 'Actiune_Executanti' relationship. 0 related 'Actiune_Executanti_Source' were found. 1 'Actiune_Executanti_Source' is expected.

我试过 Entity(Actiune).State = EntityState.Modified,但没有结果。

我有一个主要的 POCO:

  public class Cerere
    {
        public int Id { get; set; }
        ...            
        public virtual ICollection<Actiune> Actiuni { get; set; }
        ...

    }

Actiune 类看起来像这样

public class Actiune
    {
        public int Id { get; set; }
        public DateTime Data { get; set; }
        public String  Nume { get; set; }
        public virtual ICollection<Persoana> Executanti { get; set; }
        public String Stadiu { get; set; }
        public String  Obs { get; set; }
    }

还有佩索阿娜:

public class Persoana
    {

        public int Id { get; set; }
        public DateTime Data { get; set; }
        public String Nume { get; set; }
    }

【问题讨论】:

    标签: entity-framework asp.net-mvc-4 ef-code-first


    【解决方案1】:

    在您的模型中,Cerere 没有名为 Autorizare 的属性;但是它确实有一个名为 Actiuni。哪个是 Actiune 而不是 Persoana 类型,这是您要添加的内容。请发布类定义的其余部分。

    【讨论】:

    • 在我的 Cerere:公共虚拟 ICollection Autorizare { get;放; }
    • 您是否尝试过将 cerere entitystate 设置为已修改? EF 需要知道您已经修改了 cerere 对象,否则它将尝试插入角色对象而不更新 cerere 对象。
    猜你喜欢
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 2023-04-09
    • 2016-05-14
    • 2015-04-26
    • 2021-12-03
    • 2013-06-25
    • 1970-01-01
    相关资源
    最近更新 更多