实体框架无法获取实体并提供“对象的密钥不匹配..”错误

时间:2013-02-12 15:47:58

标签: repository domain-driven-design entity-framework-5

我被困在我的项目中,非常感谢任何帮助。我使用 EF 5 Code-First 方法。

这是我的基础实体:

...
public virtual Guid Id
    {
        get
        {
            return _id;
        }
        protected set { }

    }

public virtual bool IsEnabled { get; set; }
...

我的实体:

...
public string CountryName { get; set; }
public string CountryCode { get; set; }
public Coordinate CountryCoordinate { get; set; }
public virtual ICollection<City> Cities
{
    get
    {
        if (_cities == null)
        {
            _cities = new HashSet<City>();
        }

        return _cities;
    }
    private set
    {
        _cities = new HashSet<City>(value);
    }
}
...

它的配置:

public CountryEntityConfiguration()
{
this.HasKey(c => c.Id);

this.Property(c => c.CountryName)
    .HasMaxLength(64)
    .IsRequired();

this.Property(c => c.CountryCode)
    .HasMaxLength(4)
    .IsRequired();

this.HasMany(c => c.Cities)
    .WithRequired()
    .HasForeignKey(ci => ci.CountryId)
    .WillCascadeOnDelete(true);
}

存储库还有其他东西,坐标值对象和城市等都有复杂类型。

现在,当我尝试通过CountryRepository调用GetEntity(Guid Id)时,我收到错误消息:

  

属于对象键的属性的值不匹配   ObjectContext中存储的相应属性值。这个   如果属于键的属性返回不一致,则可能发生   或不正确的值或更改后未调用DetectChanges   属于作为钥匙一部分的财产。

我已经搜索了很多,但每个答案都是关于组合PK,空列等。虽然testin我种子数据库,可以看到行和列都没问题。

那么我做错了什么,有什么想法?

2 个答案:

答案 0 :(得分:5)

好吧最后我可以搞清楚。它是具有空setter的实体基础导致问题。不知怎的(可能是经过几个小时的工作)我跳过了Id的setter函数。因此,向Id属性添加_id = value可以解决问题。呼..!

public virtual Guid Id
{
    get { return _id; }
    protected set { _id = value }
}

答案 1 :(得分:0)

我有相同的异常消息,但原因却截然不同。 我有一个字符串ID列,该列被尾随空格污染。尝试查看您的ID列中的值是否包含空格。