0

[将 Code First DbContext 与 Entity Framework 5.0 RC 一起使用]

具有从其导航属性派生的 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.

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

4

1 回答 1

1

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

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

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

于 2012-06-13T19:55:59.883 回答