【问题标题】:InvalidOperationException on Find if primary key calculated using child foreign keys如果使用子外键计算主键,则查找时出现 InvalidOperationException
【发布时间】:2012-06-13 15:31:03
【问题描述】:

[在实体框架 5.0 RC 中使用 Code First DbContext]

ID 派生自其导航属性的实体

public class Domain
{
    private string _id;
    private SecondLevelDomain _secondLevelDomain;
    private TopLevelDomain _topLevelDomain;

    public string Id
    {
        get
        {
            // Trigger setter synthesis
            Id = null;
            return _id;
        }
        set
        {
            string parentId = String.Empty;
            if (Sld.Id != null)
                output += Sld.Id + " ";
            if (Tld.Id != null)
                output += Tld.Id;
            _id = parentId;
        }
    }

    public string SecondLevelDomainId
    {
        get;
        set;
    }

    [ForeignKey("SecondLevelDomainId")]
    public SecondLevelDomain Sld
    {
        get 
        { 
            return _secondLevelDomain 
            ?? (_secondLevelDomain = new SecondLevelDomain());
        }
        set 
        { 
            Debug.WriteLine("Foreign Setter Not Called Before Its Too Late");
            _secondLevelDomain = value;
        }
    }

    public string TopLevelDomainId
    {
        get;
        set;
    }

    [ForeignKey("TopLevelDomainId")]
    public TopLevelDomain Tld
    {
        get 
        { 
             return _topLevelDomain 
             ?? (_topLevelDomain = new TopLevelDomain()); 
        }
        set { _topLevelDomain = value; }
    }
}

从数据库创建域时父 ID 评估为空

public CheckDomainInDatabase(string domainId) {
    var domainFromDatabase = Repositor.Domains.Find(domainId);
}
  • InvalidOperationException: The value of a property that is part of an object's key does not match the corresponding property value stored in the ObjectContext. This can occur if properties that are part of the key return inconsistent or incorrect values or if DetectChanges is not called after changes are made to a property that is part of the key.

我需要能够使用聚合标识符检索这些域,因为我需要修改它们的一些其他属性(未显示) - 但这个错误让我偏离了轨道......

【问题讨论】:

    标签: c# .net sql entity-framework orm


    【解决方案1】:

    您不能更改现有附加实体的键。一旦实体被插入,它的密钥就固定了——它永远不会改变。如果您需要更改附加实体的键,则必须创建该实体的克隆并将其作为新实体插入。

    实体框架中实体的主要规则是它必须是唯一可识别的,并且这种识别不能改变。您的类不是实体框架的有效实体。

    顺便说一句。您创建的内容与使用 Sld.IdTld.Id 作为实体的复合主键相同,这对于检查您的实体模型或数据库架构的每个人来说至少是清楚的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-17
      • 2012-03-01
      • 1970-01-01
      • 2020-05-19
      • 1970-01-01
      • 1970-01-01
      • 2016-10-01
      相关资源
      最近更新 更多