实体框架无法获取实体并给出“对象的键不匹配..”错误

Kad*_*r.K 3 domain-driven-design repository entity-framework-5

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

这是我的基本实体:

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

    }

public virtual bool IsEnabled { get; set; }
...
Run Code Online (Sandbox Code Playgroud)

而我的实体:

...
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);
    }
}
...
Run Code Online (Sandbox Code Playgroud)

它的配置:

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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

作为对象键一部分的属性值与存储在ObjectContext中的相应属性值不匹配。如果作为键的一部分的属性返回不一致或不正确的值,或者在对作为键的一部分的属性进行更改之后未调用DetectChanges,则可能会发生这种情况。

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

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

Kad*_*r.K 5

好吧,最终我能弄清楚。这是带有空设置器的实体库引起的问题。不知何故(可能是工作了几个小时),我跳过了ID的setter函数。因此,将_id = value添加到Id属性即可解决此问题。ew!。!

public virtual Guid Id
{
    get { return _id; }
    protected set { _id = value }
}
Run Code Online (Sandbox Code Playgroud)