gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 02:30:17 24 4
gpt4 key购买 nike

我被困在我的项目中,非常感谢任何帮助。我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com