Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Cannot Get Entity and Gives "Object's Key Does Not Match.." Error

I am stucked in my project and would really appreciate any help. I am using EF 5 Code-First approach.

Here is my base entity:

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

    }

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

And my entity:

...
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);
    }
}
...

And it's configuration:

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);
}

There are other stuff for repository, complex type for coordinate value object and cities etc.

Now when I try to call GetEntity(Guid Id) over CountryRepository I get an error saying:

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.

I have searched a lot but every answer was about combined PK's, empty columns etc. While testin I seed the DB and can see that rows and columns are ok.

So what did I have done completely wrong, any ideas?

like image 305
Kadir.K Avatar asked Jun 21 '26 21:06

Kadir.K


1 Answers

Ok finally I could figure it out. It was the entity base with empty setter causing the problem. Somehow (may be after hours of work) I skipped the setter function for the Id. So adding _id = value to the Id property solved the problem. Phew..!

public virtual Guid Id
{
    get { return _id; }
    protected set { _id = value }
}
like image 186
Kadir.K Avatar answered Jun 25 '26 12:06

Kadir.K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!