repository - Entity Framework 无法获取实体并给出 "Object' s Key Does Not Match..”错误

标签 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) 时,我收到一条错误消息:

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.

我搜索了很多,但每个答案都是关于组合 PK、空列等的。在测试时,我为数据库播种,可以看到行和列都正常。

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

最佳答案

好吧,我终于明白了。这是带有空 setter 的实体库导致了问题。不知何故(可能是下类后)我跳过了 Id 的 setter 函数。所以将 _id = value 添加到 Id 属性解决了这个问题。呸……!

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

关于repository - Entity Framework 无法获取实体并给出 "Object' s Key Does Not Match..”错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836295/

相关文章:

c# - 设置默认的 DateTimeOffset 值?

c# - Entity Framework 5 和 XElement 字段

maven - 如何在Sonatype Nexus上启用CORS?

asp.net-mvc - MVC3 设计 - 存储库模式和服务层

java - 域驱动开发中的正确 URL

domain-driven-design - DDD : inter-domain referencing design issue?

.net - 当对找不到的实体发出命令时,适当的 .NET 异常类型是什么?

c# - 数据库不创建记录

c# - 使用内存中的 sql lite 单元测试流利的 nhibernate 存储库 - 没有这样的表错误

Maven - 完全禁用本地存储库,只转到远程